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
unknown
date_merged
unknown
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
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Compilers/VisualBasic/Portable/Emit/SymbolAdapter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic #If DEBUG Then Partial Friend MustInherit Class SymbolAdapter #Else Partial Friend Class Symbol #End If Implements Cci.IReference Friend Overridable Function IReferenceAsDefinition(context As EmitContext) As Cci.IDefinition _ Implements Cci.IReference.AsDefinition Throw ExceptionUtilities.Unreachable End Function Private Function IReferenceGetInternalSymbol() As CodeAnalysis.Symbols.ISymbolInternal Implements Cci.IReference.GetInternalSymbol Return AdaptedSymbol End Function Friend Overridable Sub IReferenceDispatch(visitor As Cci.MetadataVisitor) _ Implements Cci.IReference.Dispatch Throw ExceptionUtilities.Unreachable End Sub Private Function IReferenceGetAttributes(context As EmitContext) As IEnumerable(Of Cci.ICustomAttribute) Implements Cci.IReference.GetAttributes Return AdaptedSymbol.GetCustomAttributesToEmit(DirectCast(context.Module, PEModuleBuilder).CompilationState) End Function End Class Partial Friend Class Symbol #If DEBUG Then Friend Function GetCciAdapter() As SymbolAdapter Return GetCciAdapterImpl() End Function Protected Overridable Function GetCciAdapterImpl() As SymbolAdapter Throw ExceptionUtilities.Unreachable End Function #Else Friend ReadOnly Property AdaptedSymbol As Symbol Get Return Me End Get End Property Friend Function GetCciAdapter() As Symbol Return Me End Function #End If Private Function ISymbolInternalGetCciAdapter() As Cci.IReference Implements CodeAnalysis.Symbols.ISymbolInternal.GetCciAdapter Return GetCciAdapter() End Function ''' <summary> ''' Return whether the symbol is either the original definition ''' or distinct from the original. Intended for use in Debug.Assert ''' only since it may include a deep comparison. ''' </summary> Friend Function IsDefinitionOrDistinct() As Boolean Return Me.IsDefinition OrElse Not Me.Equals(Me.OriginalDefinition) End Function Friend Overridable Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) Return GetCustomAttributesToEmit(compilationState, emittingAssemblyAttributesInNetModule:=False) End Function Friend Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState, emittingAssemblyAttributesInNetModule As Boolean) As IEnumerable(Of VisualBasicAttributeData) Debug.Assert(Me.Kind <> SymbolKind.Assembly) Dim synthesized As ArrayBuilder(Of SynthesizedAttributeData) = Nothing AddSynthesizedAttributes(compilationState, synthesized) Return GetCustomAttributesToEmit(Me.GetAttributes(), synthesized, isReturnType:=False, emittingAssemblyAttributesInNetModule:=emittingAssemblyAttributesInNetModule) End Function ''' <summary> ''' Returns a list of attributes to emit to CustomAttribute table. ''' </summary> Friend Function GetCustomAttributesToEmit(userDefined As ImmutableArray(Of VisualBasicAttributeData), synthesized As ArrayBuilder(Of SynthesizedAttributeData), isReturnType As Boolean, emittingAssemblyAttributesInNetModule As Boolean) As IEnumerable(Of VisualBasicAttributeData) ' PERF: Avoid creating an iterator for the common case of no attributes. If userDefined.IsEmpty AndAlso synthesized Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of VisualBasicAttributeData)() End If Return GetCustomAttributesToEmitIterator(userDefined, synthesized, isReturnType, emittingAssemblyAttributesInNetModule) End Function Private Iterator Function GetCustomAttributesToEmitIterator(userDefined As ImmutableArray(Of VisualBasicAttributeData), synthesized As ArrayBuilder(Of SynthesizedAttributeData), isReturnType As Boolean, emittingAssemblyAttributesInNetModule As Boolean) As IEnumerable(Of VisualBasicAttributeData) If synthesized IsNot Nothing Then For Each attribute In synthesized Debug.Assert(attribute.ShouldEmitAttribute(Me, isReturnType, emittingAssemblyAttributesInNetModule:=False)) Yield attribute Next synthesized.Free() End If For i = 0 To userDefined.Length - 1 Dim attribute As VisualBasicAttributeData = userDefined(i) If Me.Kind = SymbolKind.Assembly Then ' We need to filter out duplicate assembly attributes, ' i.e. attributes that bind to the same constructor and have identical arguments. If DirectCast(Me, SourceAssemblySymbol).IsIndexOfDuplicateAssemblyAttribute(i) Then Continue For End If End If If attribute.ShouldEmitAttribute(Me, isReturnType, emittingAssemblyAttributesInNetModule) Then Yield attribute End If Next End Function ''' <summary> ''' Checks if this symbol is a definition and its containing module is a SourceModuleSymbol. ''' </summary> <Conditional("DEBUG")> Protected Friend Sub CheckDefinitionInvariant() ' can't be generic instantiation Debug.Assert(Me.IsDefinition) ' must be declared in the module we are building Debug.Assert(TypeOf Me.ContainingModule Is SourceModuleSymbol) End Sub End Class #If DEBUG Then Partial Friend Class SymbolAdapter Friend MustOverride ReadOnly Property AdaptedSymbol As Symbol Public NotOverridable Overrides Function ToString() As String Return AdaptedSymbol.ToString() End Function Public NotOverridable Overrides Function Equals(obj As Object) As Boolean ' It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. Throw Roslyn.Utilities.ExceptionUtilities.Unreachable End Function Public NotOverridable Overrides Function GetHashCode() As Integer ' It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. Throw Roslyn.Utilities.ExceptionUtilities.Unreachable End Function <Conditional("DEBUG")> Protected Friend Sub CheckDefinitionInvariant() AdaptedSymbol.CheckDefinitionInvariant() End Sub Friend Function IsDefinitionOrDistinct() As Boolean Return AdaptedSymbol.IsDefinitionOrDistinct() End Function End Class #End If End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic #If DEBUG Then Partial Friend MustInherit Class SymbolAdapter #Else Partial Friend Class Symbol #End If Implements Cci.IReference Friend Overridable Function IReferenceAsDefinition(context As EmitContext) As Cci.IDefinition _ Implements Cci.IReference.AsDefinition Throw ExceptionUtilities.Unreachable End Function Private Function IReferenceGetInternalSymbol() As CodeAnalysis.Symbols.ISymbolInternal Implements Cci.IReference.GetInternalSymbol Return AdaptedSymbol End Function Friend Overridable Sub IReferenceDispatch(visitor As Cci.MetadataVisitor) _ Implements Cci.IReference.Dispatch Throw ExceptionUtilities.Unreachable End Sub Private Function IReferenceGetAttributes(context As EmitContext) As IEnumerable(Of Cci.ICustomAttribute) Implements Cci.IReference.GetAttributes Return AdaptedSymbol.GetCustomAttributesToEmit(DirectCast(context.Module, PEModuleBuilder).CompilationState) End Function End Class Partial Friend Class Symbol #If DEBUG Then Friend Function GetCciAdapter() As SymbolAdapter Return GetCciAdapterImpl() End Function Protected Overridable Function GetCciAdapterImpl() As SymbolAdapter Throw ExceptionUtilities.Unreachable End Function #Else Friend ReadOnly Property AdaptedSymbol As Symbol Get Return Me End Get End Property Friend Function GetCciAdapter() As Symbol Return Me End Function #End If Private Function ISymbolInternalGetCciAdapter() As Cci.IReference Implements CodeAnalysis.Symbols.ISymbolInternal.GetCciAdapter Return GetCciAdapter() End Function ''' <summary> ''' Return whether the symbol is either the original definition ''' or distinct from the original. Intended for use in Debug.Assert ''' only since it may include a deep comparison. ''' </summary> Friend Function IsDefinitionOrDistinct() As Boolean Return Me.IsDefinition OrElse Not Me.Equals(Me.OriginalDefinition) End Function Friend Overridable Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) Return GetCustomAttributesToEmit(compilationState, emittingAssemblyAttributesInNetModule:=False) End Function Friend Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState, emittingAssemblyAttributesInNetModule As Boolean) As IEnumerable(Of VisualBasicAttributeData) Debug.Assert(Me.Kind <> SymbolKind.Assembly) Dim synthesized As ArrayBuilder(Of SynthesizedAttributeData) = Nothing AddSynthesizedAttributes(compilationState, synthesized) Return GetCustomAttributesToEmit(Me.GetAttributes(), synthesized, isReturnType:=False, emittingAssemblyAttributesInNetModule:=emittingAssemblyAttributesInNetModule) End Function ''' <summary> ''' Returns a list of attributes to emit to CustomAttribute table. ''' </summary> Friend Function GetCustomAttributesToEmit(userDefined As ImmutableArray(Of VisualBasicAttributeData), synthesized As ArrayBuilder(Of SynthesizedAttributeData), isReturnType As Boolean, emittingAssemblyAttributesInNetModule As Boolean) As IEnumerable(Of VisualBasicAttributeData) ' PERF: Avoid creating an iterator for the common case of no attributes. If userDefined.IsEmpty AndAlso synthesized Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of VisualBasicAttributeData)() End If Return GetCustomAttributesToEmitIterator(userDefined, synthesized, isReturnType, emittingAssemblyAttributesInNetModule) End Function Private Iterator Function GetCustomAttributesToEmitIterator(userDefined As ImmutableArray(Of VisualBasicAttributeData), synthesized As ArrayBuilder(Of SynthesizedAttributeData), isReturnType As Boolean, emittingAssemblyAttributesInNetModule As Boolean) As IEnumerable(Of VisualBasicAttributeData) If synthesized IsNot Nothing Then For Each attribute In synthesized Debug.Assert(attribute.ShouldEmitAttribute(Me, isReturnType, emittingAssemblyAttributesInNetModule:=False)) Yield attribute Next synthesized.Free() End If For i = 0 To userDefined.Length - 1 Dim attribute As VisualBasicAttributeData = userDefined(i) If Me.Kind = SymbolKind.Assembly Then ' We need to filter out duplicate assembly attributes, ' i.e. attributes that bind to the same constructor and have identical arguments. If DirectCast(Me, SourceAssemblySymbol).IsIndexOfDuplicateAssemblyAttribute(i) Then Continue For End If End If If attribute.ShouldEmitAttribute(Me, isReturnType, emittingAssemblyAttributesInNetModule) Then Yield attribute End If Next End Function ''' <summary> ''' Checks if this symbol is a definition and its containing module is a SourceModuleSymbol. ''' </summary> <Conditional("DEBUG")> Protected Friend Sub CheckDefinitionInvariant() ' can't be generic instantiation Debug.Assert(Me.IsDefinition) ' must be declared in the module we are building Debug.Assert(TypeOf Me.ContainingModule Is SourceModuleSymbol) End Sub End Class #If DEBUG Then Partial Friend Class SymbolAdapter Friend MustOverride ReadOnly Property AdaptedSymbol As Symbol Public NotOverridable Overrides Function ToString() As String Return AdaptedSymbol.ToString() End Function Public NotOverridable Overrides Function Equals(obj As Object) As Boolean ' It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. Throw Roslyn.Utilities.ExceptionUtilities.Unreachable End Function Public NotOverridable Overrides Function GetHashCode() As Integer ' It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. Throw Roslyn.Utilities.ExceptionUtilities.Unreachable End Function <Conditional("DEBUG")> Protected Friend Sub CheckDefinitionInvariant() AdaptedSymbol.CheckDefinitionInvariant() End Sub Friend Function IsDefinitionOrDistinct() As Boolean Return AdaptedSymbol.IsDefinitionOrDistinct() End Function End Class #End If End Namespace
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Compilers/Server/VBCSCompilerTests/BuildProtocolTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class BuildProtocolTest : TestBase { private void VerifyShutdownRequest(BuildRequest request) { Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ReadWriteCompleted() { var response = new CompletedBuildResponse(42, utf8output: false, output: "a string"); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = (CompletedBuildResponse)(await BuildResponse.ReadAsync(memoryStream, default(CancellationToken))); Assert.Equal(42, read.ReturnCode); Assert.False(read.Utf8Output); Assert.Equal("a string", read.Output); } [Fact] public async Task ReadWriteRequest() { var request = new BuildRequest( RequestLanguage.VisualBasicCompile, "HashValue", ImmutableArray.Create( new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: "directory"), new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 1, value: "file"))); var memoryStream = new MemoryStream(); await request.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, default(CancellationToken)); Assert.Equal(RequestLanguage.VisualBasicCompile, read.Language); Assert.Equal("HashValue", read.CompilerHash); Assert.Equal(2, read.Arguments.Count); Assert.Equal(BuildProtocolConstants.ArgumentId.CurrentDirectory, read.Arguments[0].ArgumentId); Assert.Equal(0, read.Arguments[0].ArgumentIndex); Assert.Equal("directory", read.Arguments[0].Value); Assert.Equal(BuildProtocolConstants.ArgumentId.CommandLineArgument, read.Arguments[1].ArgumentId); Assert.Equal(1, read.Arguments[1].ArgumentIndex); Assert.Equal("file", read.Arguments[1].Value); } [Fact] public void ShutdownMessage() { var request = BuildRequest.CreateShutdown(); VerifyShutdownRequest(request); Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ShutdownRequestWriteRead() { var memoryStream = new MemoryStream(); var request = BuildRequest.CreateShutdown(); await request.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, CancellationToken.None); VerifyShutdownRequest(read); } [Fact] public async Task ShutdownResponseWriteRead() { var response = new ShutdownBuildResponse(42); Assert.Equal(BuildResponse.ResponseType.Shutdown, response.Type); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildResponse.ReadAsync(memoryStream, CancellationToken.None); Assert.Equal(BuildResponse.ResponseType.Shutdown, read.Type); var typed = (ShutdownBuildResponse)read; Assert.Equal(42, typed.ServerProcessId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class BuildProtocolTest : TestBase { private void VerifyShutdownRequest(BuildRequest request) { Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ReadWriteCompleted() { var response = new CompletedBuildResponse(42, utf8output: false, output: "a string"); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = (CompletedBuildResponse)(await BuildResponse.ReadAsync(memoryStream, default(CancellationToken))); Assert.Equal(42, read.ReturnCode); Assert.False(read.Utf8Output); Assert.Equal("a string", read.Output); } [Fact] public async Task ReadWriteRequest() { var request = new BuildRequest( RequestLanguage.VisualBasicCompile, "HashValue", ImmutableArray.Create( new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: "directory"), new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 1, value: "file"))); var memoryStream = new MemoryStream(); await request.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, default(CancellationToken)); Assert.Equal(RequestLanguage.VisualBasicCompile, read.Language); Assert.Equal("HashValue", read.CompilerHash); Assert.Equal(2, read.Arguments.Count); Assert.Equal(BuildProtocolConstants.ArgumentId.CurrentDirectory, read.Arguments[0].ArgumentId); Assert.Equal(0, read.Arguments[0].ArgumentIndex); Assert.Equal("directory", read.Arguments[0].Value); Assert.Equal(BuildProtocolConstants.ArgumentId.CommandLineArgument, read.Arguments[1].ArgumentId); Assert.Equal(1, read.Arguments[1].ArgumentIndex); Assert.Equal("file", read.Arguments[1].Value); } [Fact] public void ShutdownMessage() { var request = BuildRequest.CreateShutdown(); VerifyShutdownRequest(request); Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ShutdownRequestWriteRead() { var memoryStream = new MemoryStream(); var request = BuildRequest.CreateShutdown(); await request.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, CancellationToken.None); VerifyShutdownRequest(read); } [Fact] public async Task ShutdownResponseWriteRead() { var response = new ShutdownBuildResponse(42); Assert.Equal(BuildResponse.ResponseType.Shutdown, response.Type); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildResponse.ReadAsync(memoryStream, CancellationToken.None); Assert.Equal(BuildResponse.ResponseType.Shutdown, read.Type); var typed = (ShutdownBuildResponse)read; Assert.Equal(42, typed.ServerProcessId); } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/EditorFeatures/Core.Wpf/Suggestions/SyncSuggestedActionsSource.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class SuggestedActionsSourceProvider { private partial class SyncSuggestedActionsSource : SuggestedActionsSource { public SyncSuggestedActionsSource( IThreadingContext threadingContext, IGlobalOptionService globalOptions, SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer, ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry) : base(threadingContext, globalOptions, owner, textView, textBuffer, suggestedActionCategoryRegistry) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class SuggestedActionsSourceProvider { private partial class SyncSuggestedActionsSource : SuggestedActionsSource { public SyncSuggestedActionsSource( IThreadingContext threadingContext, IGlobalOptionService globalOptions, SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer, ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry) : base(threadingContext, globalOptions, owner, textView, textBuffer, suggestedActionCategoryRegistry) { } } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.FieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents a baking field for an anonymous type template property symbol. /// </summary> private sealed class AnonymousTypeFieldSymbol : FieldSymbol { private readonly PropertySymbol _property; public AnonymousTypeFieldSymbol(PropertySymbol property) { Debug.Assert((object)property != null); _property = property; } internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { return _property.TypeWithAnnotations; } public override string Name { get { return GeneratedNames.MakeAnonymousTypeBackingFieldName(_property.Name); } } public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; internal override bool HasSpecialName { get { return false; } } internal override bool HasRuntimeSpecialName { get { return false; } } internal override bool IsNotSerialized { get { return false; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return null; } } internal override int? TypeLayoutOffset { get { return null; } } public override Symbol AssociatedSymbol { get { return _property; } } public override bool IsReadOnly { get { return true; } } public override bool IsVolatile { get { return false; } } public override bool IsConst { get { return false; } } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) { return null; } public override Symbol ContainingSymbol { get { return _property.ContainingType; } } public override NamedTypeSymbol ContainingType { get { return _property.ContainingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Private; } } public override bool IsStatic { get { return false; } } public override bool IsImplicitlyDeclared { get { return true; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingSymbol).Manager; AddSynthesizedAttribute(ref attributes, manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create( new TypedConstant(manager.System_Diagnostics_DebuggerBrowsableState, TypedConstantKind.Enum, DebuggerBrowsableState.Never)))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents a baking field for an anonymous type template property symbol. /// </summary> private sealed class AnonymousTypeFieldSymbol : FieldSymbol { private readonly PropertySymbol _property; public AnonymousTypeFieldSymbol(PropertySymbol property) { Debug.Assert((object)property != null); _property = property; } internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { return _property.TypeWithAnnotations; } public override string Name { get { return GeneratedNames.MakeAnonymousTypeBackingFieldName(_property.Name); } } public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; internal override bool HasSpecialName { get { return false; } } internal override bool HasRuntimeSpecialName { get { return false; } } internal override bool IsNotSerialized { get { return false; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return null; } } internal override int? TypeLayoutOffset { get { return null; } } public override Symbol AssociatedSymbol { get { return _property; } } public override bool IsReadOnly { get { return true; } } public override bool IsVolatile { get { return false; } } public override bool IsConst { get { return false; } } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) { return null; } public override Symbol ContainingSymbol { get { return _property.ContainingType; } } public override NamedTypeSymbol ContainingType { get { return _property.ContainingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Private; } } public override bool IsStatic { get { return false; } } public override bool IsImplicitlyDeclared { get { return true; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingSymbol).Manager; AddSynthesizedAttribute(ref attributes, manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create( new TypedConstant(manager.System_Diagnostics_DebuggerBrowsableState, TypedConstantKind.Enum, DebuggerBrowsableState.Never)))); } } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/EditorFeatures/VisualBasic/AutomaticEndConstructCorrection/AutomaticEndConstructSet.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticEndConstructCorrection Friend Class AutomaticEndConstructSet Private Shared ReadOnly s_set As HashSet(Of String) = New HashSet(Of String)(CaseInsensitiveComparison.Comparer) _ From {"structure", "enum", "interface", "class", "module", "namespace", "sub", "function", "get", "set"} Public Shared Function Contains(keyword As String) As Boolean Return s_set.Contains(keyword) 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticEndConstructCorrection Friend Class AutomaticEndConstructSet Private Shared ReadOnly s_set As HashSet(Of String) = New HashSet(Of String)(CaseInsensitiveComparison.Comparer) _ From {"structure", "enum", "interface", "class", "module", "namespace", "sub", "function", "get", "set"} Public Shared Function Contains(keyword As String) As Boolean Return s_set.Contains(keyword) End Function End Class End Namespace
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.OrderModifiers { internal abstract class AbstractOrderModifiersDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private readonly ISyntaxFacts _syntaxFacts; private readonly Option2<CodeStyleOption2<string>> _option; private readonly AbstractOrderModifiersHelpers _helpers; protected AbstractOrderModifiersDiagnosticAnalyzer( ISyntaxFacts syntaxFacts, Option2<CodeStyleOption2<string>> option, AbstractOrderModifiersHelpers helpers, string language) : base(IDEDiagnosticIds.OrderModifiersDiagnosticId, EnforceOnBuildValues.OrderModifiers, option, language, new LocalizableResourceString(nameof(AnalyzersResources.Order_modifiers), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Modifiers_are_not_ordered), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; _option = option; _helpers = helpers; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree); private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { var option = context.GetOption(_option); if (!_helpers.TryGetOrComputePreferredOrder(option.Value, out var preferredOrder)) { return; } var root = context.Tree.GetRoot(context.CancellationToken); Recurse(context, preferredOrder, option.Notification.Severity, root); } protected abstract void Recurse( SyntaxTreeAnalysisContext context, Dictionary<int, int> preferredOrder, ReportDiagnostic severity, SyntaxNode root); protected void CheckModifiers( SyntaxTreeAnalysisContext context, Dictionary<int, int> preferredOrder, ReportDiagnostic severity, SyntaxNode memberDeclaration) { var modifiers = _syntaxFacts.GetModifiers(memberDeclaration); if (!AbstractOrderModifiersHelpers.IsOrdered(preferredOrder, modifiers)) { if (severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden) { // If the severity is hidden, put the marker on all the modifiers so that the // user can bring up the fix anywhere in the modifier list. context.ReportDiagnostic( Diagnostic.Create(Descriptor, context.Tree.GetLocation( TextSpan.FromBounds(modifiers.First().SpanStart, modifiers.Last().Span.End)))); } else { // If the Severity is not hidden, then just put the user visible portion on the // first token. That way we don't context.ReportDiagnostic( DiagnosticHelper.Create(Descriptor, modifiers.First().GetLocation(), severity, additionalLocations: null, properties: null)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.OrderModifiers { internal abstract class AbstractOrderModifiersDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private readonly ISyntaxFacts _syntaxFacts; private readonly Option2<CodeStyleOption2<string>> _option; private readonly AbstractOrderModifiersHelpers _helpers; protected AbstractOrderModifiersDiagnosticAnalyzer( ISyntaxFacts syntaxFacts, Option2<CodeStyleOption2<string>> option, AbstractOrderModifiersHelpers helpers, string language) : base(IDEDiagnosticIds.OrderModifiersDiagnosticId, EnforceOnBuildValues.OrderModifiers, option, language, new LocalizableResourceString(nameof(AnalyzersResources.Order_modifiers), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Modifiers_are_not_ordered), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; _option = option; _helpers = helpers; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree); private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { var option = context.GetOption(_option); if (!_helpers.TryGetOrComputePreferredOrder(option.Value, out var preferredOrder)) { return; } var root = context.Tree.GetRoot(context.CancellationToken); Recurse(context, preferredOrder, option.Notification.Severity, root); } protected abstract void Recurse( SyntaxTreeAnalysisContext context, Dictionary<int, int> preferredOrder, ReportDiagnostic severity, SyntaxNode root); protected void CheckModifiers( SyntaxTreeAnalysisContext context, Dictionary<int, int> preferredOrder, ReportDiagnostic severity, SyntaxNode memberDeclaration) { var modifiers = _syntaxFacts.GetModifiers(memberDeclaration); if (!AbstractOrderModifiersHelpers.IsOrdered(preferredOrder, modifiers)) { if (severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden) { // If the severity is hidden, put the marker on all the modifiers so that the // user can bring up the fix anywhere in the modifier list. context.ReportDiagnostic( Diagnostic.Create(Descriptor, context.Tree.GetLocation( TextSpan.FromBounds(modifiers.First().SpanStart, modifiers.Last().Span.End)))); } else { // If the Severity is not hidden, then just put the user visible portion on the // first token. That way we don't context.ReportDiagnostic( DiagnosticHelper.Create(Descriptor, modifiers.First().GetLocation(), severity, additionalLocations: null, properties: null)); } } } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/EditorFeatures/Core.Wpf/Interactive/InteractiveDocumentNavigationServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive { [ExportWorkspaceServiceFactory(typeof(IDocumentNavigationService), WorkspaceKind.Interactive), Shared] internal sealed class InteractiveDocumentNavigationServiceFactory : IWorkspaceServiceFactory { private readonly IDocumentNavigationService _singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InteractiveDocumentNavigationServiceFactory(IThreadingContext threadingContext) => _singleton = new InteractiveDocumentNavigationService(threadingContext); public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => _singleton; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive { [ExportWorkspaceServiceFactory(typeof(IDocumentNavigationService), WorkspaceKind.Interactive), Shared] internal sealed class InteractiveDocumentNavigationServiceFactory : IWorkspaceServiceFactory { private readonly IDocumentNavigationService _singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InteractiveDocumentNavigationServiceFactory(IThreadingContext threadingContext) => _singleton = new InteractiveDocumentNavigationService(threadingContext); public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => _singleton; } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/Core/Portable/ReplaceDocCommentTextWithTag/AbstractReplaceDocCommentTextWithTagCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ReplaceDocCommentTextWithTag { internal abstract class AbstractReplaceDocCommentTextWithTagCodeRefactoringProvider : CodeRefactoringProvider { protected abstract bool IsInXMLAttribute(SyntaxToken token); protected abstract bool IsKeyword(string text); protected abstract bool IsXmlTextToken(SyntaxToken token); protected abstract SyntaxNode ParseExpression(string text); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(span.Start, findInsideTrivia: true); if (!IsXmlTextToken(token)) { return; } if (!token.FullSpan.Contains(span)) { return; } if (IsInXMLAttribute(token)) { return; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var singleWordSpan = ExpandSpan(sourceText, span, fullyQualifiedName: false); var singleWordText = sourceText.ToString(singleWordSpan); if (singleWordText == "") { return; } // First see if they're on an appropriate keyword. if (IsKeyword(singleWordText)) { RegisterRefactoring(context, singleWordSpan, $@"<see langword=""{singleWordText}""/>"); return; } // Not a keyword, see if it semantically means anything in the current context. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = GetEnclosingSymbol(semanticModel, span.Start, cancellationToken); if (symbol == null) { return; } // See if we can expand the term out to a fully qualified name. Do this // first in case the user has something like X.memberName. We don't want // to try to bind "memberName" first as it might bind to something like // a parameter, which is not what the user intends var fullyQualifiedSpan = ExpandSpan(sourceText, span, fullyQualifiedName: true); if (fullyQualifiedSpan != singleWordSpan) { var fullyQualifiedText = sourceText.ToString(fullyQualifiedSpan); if (TryRegisterSeeCrefTagIfSymbol( context, semanticModel, token, fullyQualifiedSpan, cancellationToken)) { return; } } // Check if the single word could be binding to a type parameter or parameter // for the current symbol. var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var parameter = symbol.GetParameters().FirstOrDefault(p => syntaxFacts.StringComparer.Equals(p.Name, singleWordText)); if (parameter != null) { RegisterRefactoring(context, singleWordSpan, $@"<paramref name=""{singleWordText}""/>"); return; } var typeParameter = symbol.GetTypeParameters().FirstOrDefault(t => syntaxFacts.StringComparer.Equals(t.Name, singleWordText)); if (typeParameter != null) { RegisterRefactoring(context, singleWordSpan, $@"<typeparamref name=""{singleWordText}""/>"); return; } // Doc comments on a named type can see the members inside of it. So check // inside the named type for a member that matches. if (symbol is INamedTypeSymbol namedType) { var childMember = namedType.GetMembers().FirstOrDefault(m => syntaxFacts.StringComparer.Equals(m.Name, singleWordText)); if (childMember != null) { RegisterRefactoring(context, singleWordSpan, $@"<see cref=""{singleWordText}""/>"); return; } } // Finally, try to speculatively bind the name and see if it binds to anything // in the surrounding context. TryRegisterSeeCrefTagIfSymbol( context, semanticModel, token, singleWordSpan, cancellationToken); } private bool TryRegisterSeeCrefTagIfSymbol( CodeRefactoringContext context, SemanticModel semanticModel, SyntaxToken token, TextSpan replacementSpan, CancellationToken cancellationToken) { var sourceText = semanticModel.SyntaxTree.GetText(cancellationToken); var text = sourceText.ToString(replacementSpan); var parsed = ParseExpression(text); var foundSymbol = semanticModel.GetSpeculativeSymbolInfo(token.SpanStart, parsed, SpeculativeBindingOption.BindAsExpression).GetAnySymbol(); if (foundSymbol == null) { return false; } RegisterRefactoring(context, replacementSpan, $@"<see cref=""{text}""/>"); return true; } private static ISymbol GetEnclosingSymbol(SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); var token = root.FindToken(position); for (var node = token.Parent; node != null; node = node.Parent) { if (semanticModel.GetDeclaredSymbol(node, cancellationToken) is ISymbol declaration) { return declaration; } } return null; } private static void RegisterRefactoring( CodeRefactoringContext context, TextSpan expandedSpan, string replacement) { context.RegisterRefactoring( new MyCodeAction( string.Format(FeaturesResources.Use_0, replacement), c => ReplaceTextAsync(context.Document, expandedSpan, replacement, c)), expandedSpan); } private static async Task<Document> ReplaceTextAsync( Document document, TextSpan span, string replacement, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.Replace(span, replacement); return document.WithText(newText); } private static TextSpan ExpandSpan(SourceText sourceText, TextSpan span, bool fullyQualifiedName) { if (span.Length != 0) { return span; } var startInclusive = span.Start; var endExclusive = span.Start; while (startInclusive > 0 && ShouldExpandSpanBackwardOneCharacter(sourceText, startInclusive, fullyQualifiedName)) { startInclusive--; } while (endExclusive < sourceText.Length && ShouldExpandSpanForwardOneCharacter(sourceText, endExclusive, fullyQualifiedName)) { endExclusive++; } return TextSpan.FromBounds(startInclusive, endExclusive); } private static bool ShouldExpandSpanForwardOneCharacter( SourceText sourceText, int endExclusive, bool fullyQualifiedName) { var currentChar = sourceText[endExclusive]; if (char.IsLetterOrDigit(currentChar)) { return true; } // Only consume a dot in front of the current word if it is part of a dotted // word chain, and isn't just the end of a sentence. if (fullyQualifiedName && currentChar == '.' && endExclusive + 1 < sourceText.Length && char.IsLetterOrDigit(sourceText[endExclusive + 1])) { return true; } return false; } private static bool ShouldExpandSpanBackwardOneCharacter( SourceText sourceText, int startInclusive, bool fullyQualifiedName) { Debug.Assert(startInclusive > 0); var previousCharacter = sourceText[startInclusive - 1]; if (char.IsLetterOrDigit(previousCharacter)) { return true; } if (fullyQualifiedName && previousCharacter == '.') { return true; } return false; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ReplaceDocCommentTextWithTag { internal abstract class AbstractReplaceDocCommentTextWithTagCodeRefactoringProvider : CodeRefactoringProvider { protected abstract bool IsInXMLAttribute(SyntaxToken token); protected abstract bool IsKeyword(string text); protected abstract bool IsXmlTextToken(SyntaxToken token); protected abstract SyntaxNode ParseExpression(string text); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(span.Start, findInsideTrivia: true); if (!IsXmlTextToken(token)) { return; } if (!token.FullSpan.Contains(span)) { return; } if (IsInXMLAttribute(token)) { return; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var singleWordSpan = ExpandSpan(sourceText, span, fullyQualifiedName: false); var singleWordText = sourceText.ToString(singleWordSpan); if (singleWordText == "") { return; } // First see if they're on an appropriate keyword. if (IsKeyword(singleWordText)) { RegisterRefactoring(context, singleWordSpan, $@"<see langword=""{singleWordText}""/>"); return; } // Not a keyword, see if it semantically means anything in the current context. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = GetEnclosingSymbol(semanticModel, span.Start, cancellationToken); if (symbol == null) { return; } // See if we can expand the term out to a fully qualified name. Do this // first in case the user has something like X.memberName. We don't want // to try to bind "memberName" first as it might bind to something like // a parameter, which is not what the user intends var fullyQualifiedSpan = ExpandSpan(sourceText, span, fullyQualifiedName: true); if (fullyQualifiedSpan != singleWordSpan) { var fullyQualifiedText = sourceText.ToString(fullyQualifiedSpan); if (TryRegisterSeeCrefTagIfSymbol( context, semanticModel, token, fullyQualifiedSpan, cancellationToken)) { return; } } // Check if the single word could be binding to a type parameter or parameter // for the current symbol. var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var parameter = symbol.GetParameters().FirstOrDefault(p => syntaxFacts.StringComparer.Equals(p.Name, singleWordText)); if (parameter != null) { RegisterRefactoring(context, singleWordSpan, $@"<paramref name=""{singleWordText}""/>"); return; } var typeParameter = symbol.GetTypeParameters().FirstOrDefault(t => syntaxFacts.StringComparer.Equals(t.Name, singleWordText)); if (typeParameter != null) { RegisterRefactoring(context, singleWordSpan, $@"<typeparamref name=""{singleWordText}""/>"); return; } // Doc comments on a named type can see the members inside of it. So check // inside the named type for a member that matches. if (symbol is INamedTypeSymbol namedType) { var childMember = namedType.GetMembers().FirstOrDefault(m => syntaxFacts.StringComparer.Equals(m.Name, singleWordText)); if (childMember != null) { RegisterRefactoring(context, singleWordSpan, $@"<see cref=""{singleWordText}""/>"); return; } } // Finally, try to speculatively bind the name and see if it binds to anything // in the surrounding context. TryRegisterSeeCrefTagIfSymbol( context, semanticModel, token, singleWordSpan, cancellationToken); } private bool TryRegisterSeeCrefTagIfSymbol( CodeRefactoringContext context, SemanticModel semanticModel, SyntaxToken token, TextSpan replacementSpan, CancellationToken cancellationToken) { var sourceText = semanticModel.SyntaxTree.GetText(cancellationToken); var text = sourceText.ToString(replacementSpan); var parsed = ParseExpression(text); var foundSymbol = semanticModel.GetSpeculativeSymbolInfo(token.SpanStart, parsed, SpeculativeBindingOption.BindAsExpression).GetAnySymbol(); if (foundSymbol == null) { return false; } RegisterRefactoring(context, replacementSpan, $@"<see cref=""{text}""/>"); return true; } private static ISymbol GetEnclosingSymbol(SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); var token = root.FindToken(position); for (var node = token.Parent; node != null; node = node.Parent) { if (semanticModel.GetDeclaredSymbol(node, cancellationToken) is ISymbol declaration) { return declaration; } } return null; } private static void RegisterRefactoring( CodeRefactoringContext context, TextSpan expandedSpan, string replacement) { context.RegisterRefactoring( new MyCodeAction( string.Format(FeaturesResources.Use_0, replacement), c => ReplaceTextAsync(context.Document, expandedSpan, replacement, c)), expandedSpan); } private static async Task<Document> ReplaceTextAsync( Document document, TextSpan span, string replacement, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.Replace(span, replacement); return document.WithText(newText); } private static TextSpan ExpandSpan(SourceText sourceText, TextSpan span, bool fullyQualifiedName) { if (span.Length != 0) { return span; } var startInclusive = span.Start; var endExclusive = span.Start; while (startInclusive > 0 && ShouldExpandSpanBackwardOneCharacter(sourceText, startInclusive, fullyQualifiedName)) { startInclusive--; } while (endExclusive < sourceText.Length && ShouldExpandSpanForwardOneCharacter(sourceText, endExclusive, fullyQualifiedName)) { endExclusive++; } return TextSpan.FromBounds(startInclusive, endExclusive); } private static bool ShouldExpandSpanForwardOneCharacter( SourceText sourceText, int endExclusive, bool fullyQualifiedName) { var currentChar = sourceText[endExclusive]; if (char.IsLetterOrDigit(currentChar)) { return true; } // Only consume a dot in front of the current word if it is part of a dotted // word chain, and isn't just the end of a sentence. if (fullyQualifiedName && currentChar == '.' && endExclusive + 1 < sourceText.Length && char.IsLetterOrDigit(sourceText[endExclusive + 1])) { return true; } return false; } private static bool ShouldExpandSpanBackwardOneCharacter( SourceText sourceText, int startInclusive, bool fullyQualifiedName) { Debug.Assert(startInclusive > 0); var previousCharacter = sourceText[startInclusive - 1]; if (char.IsLetterOrDigit(previousCharacter)) { return true; } if (fullyQualifiedName && previousCharacter == '.') { return true; } return false; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ITypeSymbolExtensions { private class CollectTypeParameterSymbolsVisitor : SymbolVisitor { private readonly HashSet<ISymbol> _visited = new(); private readonly bool _onlyMethodTypeParameters; private readonly IList<ITypeParameterSymbol> _typeParameters; public CollectTypeParameterSymbolsVisitor( IList<ITypeParameterSymbol> typeParameters, bool onlyMethodTypeParameters) { _onlyMethodTypeParameters = onlyMethodTypeParameters; _typeParameters = typeParameters; } public override void DefaultVisit(ISymbol node) => throw new NotImplementedException(); public override void VisitDynamicType(IDynamicTypeSymbol symbol) { } public override void VisitArrayType(IArrayTypeSymbol symbol) { if (!_visited.Add(symbol)) { return; } symbol.ElementType.Accept(this); } public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { if (!_visited.Add(symbol)) { return; } foreach (var parameter in symbol.Signature.Parameters) { parameter.Type.Accept(this); } symbol.Signature.ReturnType.Accept(this); } public override void VisitNamedType(INamedTypeSymbol symbol) { if (_visited.Add(symbol)) { foreach (var child in symbol.GetAllTypeArguments()) { child.Accept(this); } } } public override void VisitPointerType(IPointerTypeSymbol symbol) { if (!_visited.Add(symbol)) { return; } symbol.PointedAtType.Accept(this); } public override void VisitTypeParameter(ITypeParameterSymbol symbol) { if (_visited.Add(symbol)) { if (symbol.TypeParameterKind == TypeParameterKind.Method || !_onlyMethodTypeParameters) { if (!_typeParameters.Contains(symbol)) { _typeParameters.Add(symbol); } } foreach (var constraint in symbol.ConstraintTypes) { constraint.Accept(this); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ITypeSymbolExtensions { private class CollectTypeParameterSymbolsVisitor : SymbolVisitor { private readonly HashSet<ISymbol> _visited = new(); private readonly bool _onlyMethodTypeParameters; private readonly IList<ITypeParameterSymbol> _typeParameters; public CollectTypeParameterSymbolsVisitor( IList<ITypeParameterSymbol> typeParameters, bool onlyMethodTypeParameters) { _onlyMethodTypeParameters = onlyMethodTypeParameters; _typeParameters = typeParameters; } public override void DefaultVisit(ISymbol node) => throw new NotImplementedException(); public override void VisitDynamicType(IDynamicTypeSymbol symbol) { } public override void VisitArrayType(IArrayTypeSymbol symbol) { if (!_visited.Add(symbol)) { return; } symbol.ElementType.Accept(this); } public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { if (!_visited.Add(symbol)) { return; } foreach (var parameter in symbol.Signature.Parameters) { parameter.Type.Accept(this); } symbol.Signature.ReturnType.Accept(this); } public override void VisitNamedType(INamedTypeSymbol symbol) { if (_visited.Add(symbol)) { foreach (var child in symbol.GetAllTypeArguments()) { child.Accept(this); } } } public override void VisitPointerType(IPointerTypeSymbol symbol) { if (!_visited.Add(symbol)) { return; } symbol.PointedAtType.Accept(this); } public override void VisitTypeParameter(ITypeParameterSymbol symbol) { if (_visited.Add(symbol)) { if (symbol.TypeParameterKind == TypeParameterKind.Method || !_onlyMethodTypeParameters) { if (!_typeParameters.Contains(symbol)) { _typeParameters.Add(symbol); } } foreach (var constraint in symbol.ConstraintTypes) { constraint.Accept(this); } } } } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsKeyProcessorProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Windows.Input; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.InlineHints { /// <summary> /// Key processor that allows us to toggle inline hints when a user hits Alt+F1 /// </summary> [Export(typeof(IKeyProcessorProvider))] [TextViewRole(PredefinedTextViewRoles.Interactive)] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(InlineHintsKeyProcessorProvider))] internal class InlineHintsKeyProcessorProvider : IKeyProcessorProvider { private readonly IGlobalOptionService _globalOptionService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineHintsKeyProcessorProvider(IGlobalOptionService globalOptionService) { _globalOptionService = globalOptionService; } public KeyProcessor GetAssociatedProcessor(IWpfTextView wpfTextView) => new InlineHintsKeyProcessor(_globalOptionService, wpfTextView); private class InlineHintsKeyProcessor : KeyProcessor { private readonly IGlobalOptionService _globalOptionService; private readonly IWpfTextView _view; public InlineHintsKeyProcessor(IGlobalOptionService globalOptionService, IWpfTextView view) { _globalOptionService = globalOptionService; _view = view; _view.Closed += OnViewClosed; _view.LostAggregateFocus += OnLostFocus; } private static bool IsAlt(KeyEventArgs args) => IsKey(args, Key.LeftAlt) || IsKey(args, Key.RightAlt); private static bool IsF1(KeyEventArgs args) => IsKey(args, Key.F1); private static bool IsKey(KeyEventArgs args, Key key) => args.SystemKey == key || args.Key == key; private void OnViewClosed(object sender, EventArgs e) { // Disconnect our callbacks. _view.Closed -= OnViewClosed; _view.LostAggregateFocus -= OnLostFocus; // Go back to off-mode just so we don't somehow get stuck in on-mode if the option was on when the view closed. ToggleOff(); } private void OnLostFocus(object sender, EventArgs e) { // if focus is lost then go back to normal inline-hint processing. ToggleOff(); } public override void KeyDown(KeyEventArgs args) { base.KeyDown(args); // If the user is now holding down F1, see if they're also holding down 'alt'. If so, toggle the inline hints on. if (IsF1(args) && args.KeyboardDevice.Modifiers == ModifierKeys.Alt) { ToggleOn(); } else { // Otherwise, on any other keypress toggle off. Note that this will normally be non-expensive as we // will see the option is already off and immediately exit.. ToggleOff(); } } public override void KeyUp(KeyEventArgs args) { base.KeyUp(args); // If we've lifted a key up from either character of our alt-F1 chord, then turn off the inline hints. if (IsAlt(args) || IsF1(args)) ToggleOff(); } private void ToggleOn() => Toggle(on: true); private void ToggleOff() => Toggle(on: false); private void Toggle(bool on) { // No need to do anything if we're already in the requested state var state = _globalOptionService.GetOption(InlineHintsOptions.DisplayAllOverride); if (state == on) return; // We can only enter the on-state if the user has the chord feature enabled. We can always enter the // off state though. on = on && _globalOptionService.GetOption(InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); _globalOptionService.RefreshOption(new OptionKey(InlineHintsOptions.DisplayAllOverride), on); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Windows.Input; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.InlineHints { /// <summary> /// Key processor that allows us to toggle inline hints when a user hits Alt+F1 /// </summary> [Export(typeof(IKeyProcessorProvider))] [TextViewRole(PredefinedTextViewRoles.Interactive)] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(InlineHintsKeyProcessorProvider))] internal class InlineHintsKeyProcessorProvider : IKeyProcessorProvider { private readonly IGlobalOptionService _globalOptionService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineHintsKeyProcessorProvider(IGlobalOptionService globalOptionService) { _globalOptionService = globalOptionService; } public KeyProcessor GetAssociatedProcessor(IWpfTextView wpfTextView) => new InlineHintsKeyProcessor(_globalOptionService, wpfTextView); private class InlineHintsKeyProcessor : KeyProcessor { private readonly IGlobalOptionService _globalOptionService; private readonly IWpfTextView _view; public InlineHintsKeyProcessor(IGlobalOptionService globalOptionService, IWpfTextView view) { _globalOptionService = globalOptionService; _view = view; _view.Closed += OnViewClosed; _view.LostAggregateFocus += OnLostFocus; } private static bool IsAlt(KeyEventArgs args) => IsKey(args, Key.LeftAlt) || IsKey(args, Key.RightAlt); private static bool IsF1(KeyEventArgs args) => IsKey(args, Key.F1); private static bool IsKey(KeyEventArgs args, Key key) => args.SystemKey == key || args.Key == key; private void OnViewClosed(object sender, EventArgs e) { // Disconnect our callbacks. _view.Closed -= OnViewClosed; _view.LostAggregateFocus -= OnLostFocus; // Go back to off-mode just so we don't somehow get stuck in on-mode if the option was on when the view closed. ToggleOff(); } private void OnLostFocus(object sender, EventArgs e) { // if focus is lost then go back to normal inline-hint processing. ToggleOff(); } public override void KeyDown(KeyEventArgs args) { base.KeyDown(args); // If the user is now holding down F1, see if they're also holding down 'alt'. If so, toggle the inline hints on. if (IsF1(args) && args.KeyboardDevice.Modifiers == ModifierKeys.Alt) { ToggleOn(); } else { // Otherwise, on any other keypress toggle off. Note that this will normally be non-expensive as we // will see the option is already off and immediately exit.. ToggleOff(); } } public override void KeyUp(KeyEventArgs args) { base.KeyUp(args); // If we've lifted a key up from either character of our alt-F1 chord, then turn off the inline hints. if (IsAlt(args) || IsF1(args)) ToggleOff(); } private void ToggleOn() => Toggle(on: true); private void ToggleOff() => Toggle(on: false); private void Toggle(bool on) { // No need to do anything if we're already in the requested state var state = _globalOptionService.GetOption(InlineHintsOptions.DisplayAllOverride); if (state == on) return; // We can only enter the on-state if the user has the chord feature enabled. We can always enter the // off state though. on = on && _globalOptionService.GetOption(InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); _globalOptionService.RefreshOption(new OptionKey(InlineHintsOptions.DisplayAllOverride), on); } } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/StructureKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class StructureKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Structure") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureFollowsStructureTest() Dim code = <File> Structure S End Structure | </File> VerifyRecommendationsContain(code, "Structure") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureFollowsStructureWithinClassTest() Dim code = <File> Class C Structure S End Structure | End Class </File> VerifyRecommendationsContain(code, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotInMethodDeclarationTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInNamespaceTest() VerifyRecommendationsContain(<NamespaceDeclaration>|</NamespaceDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInInterfaceTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Structure") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureFollowsMismatchedEndTest() Dim code = <File> Interface I1 End Class | End Interface </File> VerifyRecommendationsContain(code, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotInEnumTest() VerifyRecommendationsMissing(<EnumDeclaration>|</EnumDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInStructureTest() VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInModuleTest() VerifyRecommendationsContain(<ModuleDeclaration>|</ModuleDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterPartialTest() VerifyRecommendationsContain(<File>Partial |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterPublicInFileTest() VerifyRecommendationsContain(<File>Public |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterPublicInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Public |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureMissingAfterProtectedInFileTest() VerifyRecommendationsMissing(<File>Protected |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureExistsAfterProtectedInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Protected |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterFriendInFileTest() VerifyRecommendationsContain(<File>Friend |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterFriendInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Friend |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterPrivateInFileTest() VerifyRecommendationsMissing(<File>Private |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterPrivateInNestedClassTest() VerifyRecommendationsContain(<ClassDeclaration>Private |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterPrivateInNamespaceTest() VerifyRecommendationsMissing(<File> Namespace Goo Private | End Namespace</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterProtectedFriendInFileTest() VerifyRecommendationsMissing(<File>Protected Friend |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterProtectedFriendInClassTest() VerifyRecommendationsContain(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterMustOverrideOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride Overrides |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterNotOverridableOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable Overrides |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterConstTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterWriteOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterCustomTest() VerifyRecommendationsMissing(<ClassDeclaration>Custom |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "Structure") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterAsyncTest() VerifyRecommendationsMissing(<ClassDeclaration>Async |</ClassDeclaration>, "Structure") End Sub <WorkItem(20837, "https://github.com/dotnet/roslyn/issues/20837")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterAttribute() VerifyRecommendationsContain(<File>&lt;AttributeApplication&gt; |</File>, "Structure") 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class StructureKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Structure") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureFollowsStructureTest() Dim code = <File> Structure S End Structure | </File> VerifyRecommendationsContain(code, "Structure") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureFollowsStructureWithinClassTest() Dim code = <File> Class C Structure S End Structure | End Class </File> VerifyRecommendationsContain(code, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotInMethodDeclarationTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInNamespaceTest() VerifyRecommendationsContain(<NamespaceDeclaration>|</NamespaceDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInInterfaceTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Structure") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureFollowsMismatchedEndTest() Dim code = <File> Interface I1 End Class | End Interface </File> VerifyRecommendationsContain(code, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotInEnumTest() VerifyRecommendationsMissing(<EnumDeclaration>|</EnumDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInStructureTest() VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureInModuleTest() VerifyRecommendationsContain(<ModuleDeclaration>|</ModuleDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterPartialTest() VerifyRecommendationsContain(<File>Partial |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterPublicInFileTest() VerifyRecommendationsContain(<File>Public |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterPublicInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Public |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureMissingAfterProtectedInFileTest() VerifyRecommendationsMissing(<File>Protected |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureExistsAfterProtectedInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Protected |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterFriendInFileTest() VerifyRecommendationsContain(<File>Friend |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterFriendInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Friend |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterPrivateInFileTest() VerifyRecommendationsMissing(<File>Private |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterPrivateInNestedClassTest() VerifyRecommendationsContain(<ClassDeclaration>Private |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterPrivateInNamespaceTest() VerifyRecommendationsMissing(<File> Namespace Goo Private | End Namespace</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterProtectedFriendInFileTest() VerifyRecommendationsMissing(<File>Protected Friend |</File>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureAfterProtectedFriendInClassTest() VerifyRecommendationsContain(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterMustOverrideOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride Overrides |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterNotOverridableOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable Overrides |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterConstTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterWriteOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterCustomTest() VerifyRecommendationsMissing(<ClassDeclaration>Custom |</ClassDeclaration>, "Structure") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StructureNotAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "Structure") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterAsyncTest() VerifyRecommendationsMissing(<ClassDeclaration>Async |</ClassDeclaration>, "Structure") End Sub <WorkItem(20837, "https://github.com/dotnet/roslyn/issues/20837")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterAttribute() VerifyRecommendationsContain(<File>&lt;AttributeApplication&gt; |</File>, "Structure") End Sub End Class End Namespace
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./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, 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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/Core/Portable/Diagnostics/IRemoteDiagnosticAnalyzerService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.Diagnostics { internal interface IRemoteDiagnosticAnalyzerService { ValueTask<SerializableDiagnosticAnalysisResults> CalculateDiagnosticsAsync(PinnedSolutionInfo solutionInfo, DiagnosticArguments arguments, CancellationToken cancellationToken); ValueTask ReportAnalyzerPerformanceAsync(ImmutableArray<AnalyzerPerformanceInfo> snapshot, int unitCount, CancellationToken cancellationToken); } [DataContract] internal readonly struct AnalyzerPerformanceInfo { [DataMember(Order = 0)] public readonly string AnalyzerId; [DataMember(Order = 1)] public readonly bool BuiltIn; [DataMember(Order = 2)] public readonly TimeSpan TimeSpan; public AnalyzerPerformanceInfo(string analyzerId, bool builtIn, TimeSpan timeSpan) { AnalyzerId = analyzerId; BuiltIn = builtIn; TimeSpan = timeSpan; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.Diagnostics { internal interface IRemoteDiagnosticAnalyzerService { ValueTask<SerializableDiagnosticAnalysisResults> CalculateDiagnosticsAsync(PinnedSolutionInfo solutionInfo, DiagnosticArguments arguments, CancellationToken cancellationToken); ValueTask ReportAnalyzerPerformanceAsync(ImmutableArray<AnalyzerPerformanceInfo> snapshot, int unitCount, CancellationToken cancellationToken); } [DataContract] internal readonly struct AnalyzerPerformanceInfo { [DataMember(Order = 0)] public readonly string AnalyzerId; [DataMember(Order = 1)] public readonly bool BuiltIn; [DataMember(Order = 2)] public readonly TimeSpan TimeSpan; public AnalyzerPerformanceInfo(string analyzerId, bool builtIn, TimeSpan timeSpan) { AnalyzerId = analyzerId; BuiltIn = builtIn; TimeSpan = timeSpan; } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesVsPatterns.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.NullableReferenceTypes, CompilerFeature.Patterns)] public class NullableReferenceTypesVsPatterns : CSharpTestBase { private CSharpCompilation CreateNullableCompilation(string source) { return CreateCompilation(new[] { source }, options: WithNullableEnable()); } [Fact] public void VarPatternInfersNullableType() { CSharpCompilation c = CreateNullableCompilation(@" public class C { public string Field = null!; void M1() { if (this is { Field: var s }) { s.ToString(); s = null; } } void M2() { if (this is (var s) _) { s.ToString(); s = null; } } void Deconstruct(out string s) => throw null!; } "); c.VerifyDiagnostics(); } [Fact] public void ConditionalBranching_IsConstantPattern_Null() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { if (x is null) { x.ToString(); // warn } else { x.ToString(); } } } "); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_NullInverted() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { if (!(x is null)) { x.ToString(); } else { x.ToString(); // warn } } } "); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_NonNull() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { const string nonNullConstant = ""hello""; if (x is nonNullConstant) { x.ToString(); } else { x.ToString(); // warn } } } "); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_NullConstant() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { const string? nullConstant = null; if (x is nullConstant) { x.ToString(); // warn } else { x.ToString(); } } } "); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_NonConstant() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { string nonConstant = ""hello""; if (x is nonConstant) { x.ToString(); } } } "); c.VerifyDiagnostics( // (7,18): error CS0150: A constant value is expected // if (x is nonConstant) Diagnostic(ErrorCode.ERR_ConstantExpected, "nonConstant").WithLocation(7, 18), // (9,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_Null_AlreadyTestedAsNonNull() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { if (x != null) { if (x is null) { x.ToString(); // warn } else { x.ToString(); } } } } "); c.VerifyDiagnostics( // (10,17): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 17) ); } [Fact] public void ConditionalBranching_IsConstantPattern_Null_AlreadyTestedAsNull() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { if (x == null) { if (x is null) { x.ToString(); // warn } else { x.ToString(); } } } } "); c.VerifyDiagnostics( // (10,17): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 17) ); } [Fact] public void ConditionalBranching_IsDeclarationPattern_02() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { if (x is C c) { x.ToString(); c.ToString(); } else { x.ToString(); // warn } } void Test2(object x) { if (x is C c) { x.ToString(); c.ToString(); } else { x.ToString(); } } } "); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13) ); } [Fact] public void ConditionalBranching_IsVarDeclarationPattern() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { if (x is var c) { x.ToString(); // warn 1 c /*T:object?*/ .ToString(); // warn 2 c = null; } else { x.ToString(); } } void Test2(object x) { if (x is var c) { x.ToString(); c /*T:object!*/ .ToString(); } else { x.ToString(); } } } "); c.VerifyTypes(); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // c /*T:object?*/ .ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 13) ); } [Fact] public void ConditionalBranching_IsVarDeclarationPattern_Discard() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { if (x is var _) { x.ToString(); // 1 } else { x.ToString(); } } void Test2(object x) { if (x is var _) { x.ToString(); } else { x.ToString(); } } } "); c.VerifyTypes(); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13) ); } [Fact] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void ConditionalBranching_IsVarDeclarationPattern_AlreadyTestedAsNonNull() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { if (x != null) { if (x is var c) { c /*T:object!*/ .ToString(); c = null; } } } void Test2(object x) { if (x != null) { if (x is var c) { c /*T:object!*/ .ToString(); c = null; } } } } "); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void IsPattern_01() { var source = @"class C { static void F(object x) { } static void G(string s) { F(s is var o); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29909, "https://github.com/dotnet/roslyn/issues/29909")] public void IsPattern_02() { var source = @"class C { static void F(string s) { } static void G(string? s) { if (s is string t) { F(t); F(s); } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void IsPattern_AffectsNullConditionalOperator_DeclarationPattern() { var source = @"class C { static void G1(string? s) { if (s?.ToString() is string t) { s.ToString(); } else { s.ToString(); // 1 } } static void G2(string s) { if (s?.ToString() is string t) { s.ToString(); } else { s.ToString(); // 2 } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(11, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(22, 13)); } [Fact] public void IsPattern_AffectsNullConditionalOperator_NullableValueType() { var source = @"class C { static void G1(int? i) { if (i?.ToString() is string t) { i.Value.ToString(); } else { i.Value.ToString(); // 1 } } static void G2(int? i) { i = 1; if (i?.ToString() is string t) { i.Value.ToString(); } else { i.Value.ToString(); // 2 } } static void G3(int? i) { i = 1; if (i is int q) { i.Value.ToString(); } else { i.Value.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // i.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(11, 13), // (23,13): warning CS8629: Nullable value type may be null. // i.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(23, 13)); } [Fact] public void IsPattern_AffectsNullConditionalOperator_NullableValueType_Nested() { var source = @" public struct S { public int? field; } class C { static void G(S? s) { if (s?.field?.ToString() is string t) { s.Value.ToString(); s.Value.field.Value.ToString(); } else { s.Value.ToString(); // warn s.Value.field.Value.ToString(); // warn } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (17,13): warning CS8629: Nullable value type may be null. // s.Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s").WithLocation(17, 13), // (18,13): warning CS8629: Nullable value type may be null. // s.Value.field.Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s.Value.field").WithLocation(18, 13) ); } [Fact, WorkItem(28798, "https://github.com/dotnet/roslyn/issues/28798")] public void IsPattern_AffectsNullConditionalOperator_VarPattern() { var source = @"class C { static void G(string? s) { if (s?.ToString() is var t) { s.ToString(); // 1 } else { s.ToString(); } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13) ); } [Fact] public void IsPattern_AffectsNullConditionalOperator_NullConstantPattern() { var source = @"class C { static void G(string? s) { if (s?.ToString() is null) { s.ToString(); // warn } else { s.ToString(); } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13) ); } [Fact] [WorkItem(29909, "https://github.com/dotnet/roslyn/issues/29909")] [WorkItem(23944, "https://github.com/dotnet/roslyn/issues/23944")] public void PatternSwitch() { var source = @"class C { static void F(object o) { } static void G(object? x) { switch (x) { case string s: F(s); F(x); break; case object y when y is string t: F(y); F(t); F(x); break; case null: F(x); // 1 break; default: F(x); break; } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (18,19): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // F(x); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "void C.F(object o)").WithLocation(18, 19)); } [Fact] public void IsDeclarationPattern_01() { var source = @"class Program { static void F1(object x1) { if (x1 is string y1) { x1/*T:object!*/.ToString(); y1/*T:string!*/.ToString(); } x1/*T:object!*/.ToString(); } static void F2(object? x2) { if (x2 is string y2) { x2/*T:object!*/.ToString(); y2/*T:string!*/.ToString(); } x2/*T:object?*/.ToString(); // 1 } static void F3(object x3) { x3 = null; // 2 if (x3 is string y3) { x3/*T:object!*/.ToString(); y3/*T:string!*/.ToString(); } x3/*T:object?*/.ToString(); // 3 } static void F4(object? x4) { if (x4 == null) return; if (x4 is string y4) { x4/*T:object!*/.ToString(); y4/*T:string!*/.ToString(); } x4/*T:object!*/.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(19, 9), // (23,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(23, 14), // (29,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(29, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(30952, "https://github.com/dotnet/roslyn/issues/30952")] public void IsDeclarationPattern_02() { var source = @"class Program { static void F1<T, U>(T t1) where T : class where U : class { if (t1 is U u1) { t1.ToString(); u1.ToString(); } t1.ToString(); } static void F2<T, U>(T t2) where T : class? where U : class { if (t2 is U u2) { t2.ToString(); u2.ToString(); } t2.ToString(); // 1 } static void F3<T, U>(T t3) where T : class where U : class { t3 = null; // 2 if (t3 is U u3) { t3.ToString(); u3.ToString(); } t3.ToString(); // 3 } static void F4<T, U>(T t4) where T : class? where U : class { if (t4 == null) return; if (t4 is U u4) { t4.ToString(); u4.ToString(); } t4.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (23,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(23, 9), // (29,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t3 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(29, 14), // (35,9): warning CS8602: Dereference of a possibly null reference. // t3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(35, 9)); } [Fact] public void IsDeclarationPattern_03() { var source = @"class Program { static void F1<T, U>(T t1) { if (t1 is U u1) { t1.ToString(); u1.ToString(); } t1.ToString(); // 1 } static void F2<T, U>(T t2) { if (t2 == null) return; if (t2 is U u2) { t2.ToString(); u2.ToString(); } t2.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(10, 9)); } [Fact] public void IsDeclarationPattern_NeverNull_01() { var source = @"class Program { static void F1(object x1) { if (x1 is string y1) { x1.ToString(); x1?.ToString(); y1.ToString(); y1?.ToString(); } x1.ToString(); // 1 (because of x1?. above) } static void F2(object? x2) { if (x2 is string y2) { x2.ToString(); x2?.ToString(); y2.ToString(); y2?.ToString(); } x2.ToString(); // 2 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 (because of x1?. above) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(23, 9)); } [Fact] public void IsDeclarationPattern_Unassigned_01() { var source = @"class Program { static void F1(object x1) { if (x1 is string y1) { } else { x1.ToString(); y1.ToString(); // 1 } } static void F2(object? x2) { if (x2 is string y2) { } else { x2.ToString(); // 2 y2.ToString(); // 3 } } static void F3(object x3) { x3 = null; // 4 if (x3 is string y3) { } else { x3.ToString(); // 5 y3.ToString(); // 6 } } static void F4(object? x4) { if (x4 == null) return; if (x4 is string y4) { } else { x4.ToString(); y4.ToString(); // 7 } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): error CS0165: Use of unassigned local variable 'y1' // y1.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(11, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(21, 13), // (22,13): error CS0165: Use of unassigned local variable 'y2' // y2.ToString(); // 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "y2").WithArguments("y2").WithLocation(22, 13), // (27,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(27, 14), // (33,13): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(33, 13), // (34,13): error CS0165: Use of unassigned local variable 'y3' // y3.ToString(); // 6 Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(34, 13), // (46,13): error CS0165: Use of unassigned local variable 'y4' // y4.ToString(); // 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "y4").WithArguments("y4").WithLocation(46, 13)); } [Fact] public void IsDeclarationPattern_Unassigned_02() { var source = @"class Program { static void F1(object x1) { if (x1 is string y1) { } x1.ToString(); y1.ToString(); // 1 } static void F2(object? x2) { if (x2 is string y2) { } x2.ToString(); // 2 y2.ToString(); // 3 } static void F3(object x3) { x3 = null; // 4 if (x3 is string y3) { } x3.ToString(); // 5 y3.ToString(); // 6 } static void F4(object? x4) { if (x4 == null) return; if (x4 is string y4) { } x4.ToString(); y4.ToString(); // 7 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0165: Use of unassigned local variable 'y1' // y1.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(7, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(12, 9), // (13,9): error CS0165: Use of unassigned local variable 'y2' // y2.ToString(); // 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "y2").WithArguments("y2").WithLocation(13, 9), // (17,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(17, 14), // (19,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(19, 9), // (20,9): error CS0165: Use of unassigned local variable 'y3' // y3.ToString(); // 6 Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(20, 9), // (27,9): error CS0165: Use of unassigned local variable 'y4' // y4.ToString(); // 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "y4").WithArguments("y4").WithLocation(27, 9)); } [Fact] public void UnconstrainedTypeParameter_PatternMatching() { var source = @" class C { static void F1<T>(object o, T tin) { if (o is T t1) { t1.ToString(); } else { t1 = default; } t1.ToString(); // 1 if (!(o is T t2)) { t2 = tin; } else { t2.ToString(); } t2.ToString(); // 2 if (!(o is T t3)) return; t3.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(15, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(25, 9) ); } [WorkItem(32503, "https://github.com/dotnet/roslyn/issues/32503")] [Fact] public void PatternDeclarationBreaksNullableAnalysis() { var source = @" class A { } class B : A { A M() { var s = new A(); if (s is B b) {} return s; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void InferenceWithITuplePattern() { var source = @" class A { } class B : A { A M() { var s = new A(); if (s is B b) {} return s; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void RecursivePatternNullInferenceWithDowncast_01() { var source = @" class Base { public object Value = """"; } class Derived : Base { public new object Value = """"; } class Program { void M(Base? b) { if (b is Derived { Value: null }) b.Value.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void RecursivePatternNullInferenceWithDowncast_02() { var source = @" class Base { public object Value = """"; } class Derived : Base { } class Program { void M(Base? b) { if (b is Derived { Value: null }) b.Value.ToString(); // 1 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Value").WithLocation(14, 13)); } [Fact] public void TuplePatternNullInference_01() { var source = @" class Program { void M((object, object) t) { if (t is (1, null)) { } else { t.Item2.ToString(); // 1 t.Item1.ToString(); } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(11, 13)); } [Fact] public void MultiplePathsThroughDecisionDag_01() { var source = @" class Program { bool M1(object? o, bool cond = true) { o = 1; switch (o) { case null: throw null!; case """" when M1(o = null): break; default: if (cond) o.ToString(); // 1 break; } return cond; } bool M2(object? o, bool cond = true) { o = 1; switch (o) { case """" when M2(o = null): break; default: if (cond) o.ToString(); // 2 break; } return cond; } bool M3(object? o, bool cond = true) { o = 1; switch (o) { case null: throw null!; default: if (cond) o.ToString(); break; } return cond; } bool M4(object? o, bool cond = true) { o = 1; switch (o) { case null: throw null!; case """" when M4(o = null): break; case var q: q.ToString(); // 3 (!?) break; } return cond; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (14,27): warning CS8602: Dereference of a possibly null reference. // if (cond) o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(14, 27), // (28,27): warning CS8602: Dereference of a possibly null reference. // if (cond) o.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(28, 27), // (58,17): warning CS8602: Dereference of a possibly null reference. // q.ToString(); // 3 (!?) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "q").WithLocation(58, 17)); } [Fact] [WorkItem(30597, "https://github.com/dotnet/roslyn/issues/30597")] [WorkItem(32414, "https://github.com/dotnet/roslyn/issues/32414")] public void NotExhaustiveForNull_01() { var source = @" class Program { void M0(object o) { var t = (o, o); _ = t switch { (null, null) => 1, (null, {}) => 2, ({}, null) => 3, ({}, {}) => 4, }; } void M1(object o) { var t = (o, o); _ = t switch // 1 not exhaustive { (null, 2) => 1, ({}, {}) => 2, }; } void M2(object o) { var t = (o, o); _ = t switch // 2 not exhaustive { (1, 2) => 1, ({}, {}) => 2, }; } void M3(object o) { var t = (o, o); _ = t switch // 3 not exhaustive { (null, 2) => 1, ({}, {}) => 2, (null, {}) => 3, }; } void M4(object o) { var t = (o, o); _ = t switch // 4 not exhaustive { { Item1: null, Item2: 2 } => 1, { Item1: {}, Item2: {} } => 2, }; } void M5(object o) { var t = (o, o); _ = t switch // 5 not exhaustive { { Item1: 1, Item2: 2 } => 1, { Item1: {}, Item2: {} } => 2, }; } void M6(object o) { var t = (o, o); _ = t switch // 6 not exhaustive { { Item1: null, Item2: 2 } => 1, { Item1: {}, Item2: {} } => 2, { Item1: null, Item2: {} } => 3, }; } void M7(object o, bool b) { _ = o switch // 7 not exhaustive { null when b => 1, {} => 2, }; } void M8(object o, bool b) { _ = o switch { null when b => 1, {} => 2, null => 3, }; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (18,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // _ = t switch // 1 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(18, 15), // (27,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // _ = t switch // 2 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(27, 15), // (36,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(not null, null)' is not covered. // _ = t switch // 3 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(not null, null)").WithLocation(36, 15), // (46,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // _ = t switch // 4 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(46, 15), // (55,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // _ = t switch // 5 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(55, 15), // (64,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(not null, null)' is not covered. // _ = t switch // 6 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(not null, null)").WithLocation(64, 15), // (73,15): warning CS8847: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern 'null' is not covered. However, a pattern with a 'when' clause might successfully match this value. // _ = o switch // 7 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen, "switch").WithArguments("null").WithLocation(73, 15)); } [Fact] [WorkItem(30597, "https://github.com/dotnet/roslyn/issues/30597")] [WorkItem(32414, "https://github.com/dotnet/roslyn/issues/32414")] public void NotExhaustiveForNull_02() { var source = @" class Test { int M1(string s1, string s2) { return (s1, s2) switch { (string x, string y) => x.Length + y.Length }; } int M2(string? s1, string s2) { return (s1, s2) switch { // 1 (string x, string y) => x.Length + y.Length }; } int M3(string s1, string? s2) { return (s1, s2) switch { // 2 (string x, string y) => x.Length + y.Length }; } int M4(string? s1, string? s2) { return (s1, s2) switch { // 3 (string x, string y) => x.Length + y.Length }; } int M5(string s1, string s2) { return (s1, s2) switch { // 4 (null, ""x"") => 1, (string x, string y) => x.Length + y.Length }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (12,25): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // return (s1, s2) switch { // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(12, 25), // (18,25): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // return (s1, s2) switch { // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(18, 25), // (24,25): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // return (s1, s2) switch { // 3 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(24, 25), // (30,25): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, "")' is not covered. // return (s1, s2) switch { // 4 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, \"\")").WithLocation(30, 25)); } [Fact, WorkItem(31881, "https://github.com/dotnet/roslyn/issues/31881")] public void NullableVsPattern_31881() { var source = @" using System; public class C { public object? AProperty { get; set; } public void M(C? input, int i) { if (input?.AProperty is string str) { Console.WriteLine(str.ToString()); switch (i) { case 1: Console.WriteLine(input?.AProperty.ToString()); break; case 2: Console.WriteLine(input.AProperty.ToString()); break; case 3: Console.WriteLine(input.ToString()); break; } } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(33499, "https://github.com/dotnet/roslyn/issues/33499")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void PatternVariablesAreNotOblivious_33499() { var source = @" class Test { static void M(object o) { if (o is string s) { } s = null; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 13) ); } [Fact] public void IsPatternAlwaysFalse() { var source = @" class Test { void M1(ref object o) { if (2 is 3) o = null; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (6,13): warning CS8519: The given expression never matches the provided pattern. // if (2 is 3) Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "2 is 3").WithLocation(6, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructWithNotBackedProperty() { var source = @" struct Point { public object X, Y; public Point Mirror => new Point { X = Y, Y = X }; bool Test => this is { X: 1, Y: 2, Mirror: { X: 2, Y: 1 } }; }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void LearnFromNullPattern_01() { var source = @" class Node { public Node Next = null!; } class Program { void M1(Node n) { if (n is null) {} n.Next.Next.Next.ToString(); // 1 } void M2(Node n) { if (n is {Next: null}) {} n.Next.Next.Next.ToString(); // 2 } void M3(Node n) { if (n is {Next: {Next: null}}) {} n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(16, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(21, 9)); } [Fact] public void LearnFromNullPattern_02() { var source = @" class Node { public Node Next = null!; } class Program { void M1(Node n) { switch (n) { case null: break; } n.Next.Next.Next.ToString(); // 1 } void M2(Node n) { switch (n) { case {Next: null}: break; } n.Next.Next.Next.ToString(); // 2 } void M3(Node n) { switch (n) { case {Next: {Next: null}}: break; } n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(16, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(21, 9)); } [Fact] public void LearnFromNullPattern_03() { var source = @" class Node { public Node Next = null!; } class Program { void M1(Node n) { _ = n switch { null => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 1 } void M2(Node n) { _ = n switch { {Next: null} => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 2 } void M3(Node n) { _ = n switch { {Next: {Next: null}} => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(16, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(21, 9)); } [Fact] public void LearnFromNullPattern_04() { var source = @" #nullable disable class Node { public Node Next = null!; } #nullable enable class Program { #nullable disable void M1(Node n) #nullable enable { _ = n switch { null => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 1 } #nullable disable void M2(Node n) #nullable enable { _ = n switch { {Next: null} => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 2 } #nullable disable void M3(Node n) #nullable enable { _ = n switch { {Next: {Next: null}} => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n").WithLocation(15, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(22, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(29, 9)); } [Fact] public void LearnFromNullPattern_05() { var source = @" class Program { void M1((string s1, string s2) n) { _ = n switch { (_, null) => n.s1.ToString(), var q => n.s1.ToString(), }; n.s1.ToString(); n.s2.ToString(); // 1 } void M2((string s1, string s2) n) { _ = n switch { (null, _) => n.s1.ToString(), // 2 (_, _) => n.s1.ToString(), }; n.s1.ToString(); // 3 n.s2.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // n.s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.s2").WithLocation(11, 9), // (16,26): warning CS8602: Dereference of a possibly null reference. // (null, _) => n.s1.ToString(), // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.s1").WithLocation(16, 26)); } [Fact] public void LearnFromNonNullPattern_01() { var source = @" class Node { public Node? Next = null; } class Program { void M1(Node? n) { if (n is {} q) n.Next.ToString(); // 1 } void M2(Node? n) { if (n is {Next: {}} q) n.Next.Next.ToString(); // 2 } void M3(Node? n) { if (n is {Next: {Next: {}}} q) n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // n.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(11, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(16, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next.Next").WithLocation(21, 13)); } [Fact] public void LearnFromNonNullPattern_02() { var source = @" class Node { public Node? Next = null; } class Program { void M1(Node? n) { switch (n) { case {} q: n.Next.ToString(); // 1 break; } } void M2(Node? n) { switch (n) { case {Next: {}} q: n.Next.Next.ToString(); // 2 break; } } void M3(Node? n) { switch (n) { case {Next: {Next: {}}} q: n.Next.Next.Next.ToString(); // 3 break; } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // n.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(11, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(17, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next.Next").WithLocation(23, 13)); } [Fact] public void LearnFromNonNullPattern_03() { var source = @" class Node { public Node? Next = null; } class Program { void M1(Node? n) { _ = n switch { {} q => n.Next.ToString(), // 1 _ => string.Empty }; } void M2(Node? n) { _ = n switch { {Next: {}} q => n.Next.Next.ToString(), // 2 _ => string.Empty }; } void M3(Node? n) { _ = n switch { {Next: {Next: {}}} q => n.Next.Next.Next.ToString(), // 3 _ => string.Empty }; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // n.Next.ToString(), // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(11, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.ToString(), // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(17, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(), // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next.Next").WithLocation(23, 13)); } [Fact] public void LearnFromNonNullPattern_04() { var source = @" class Program { void M1((string? s1, string? s2)? n) { _ = n switch { var q => n.Value.ToString(), // 1: n }; } void M2((string? s1, string? s2)? n) { _ = n switch { (_, _) => n.Value.s1.ToString(), // 2: n.Value.s1 _ => n.Value.ToString(), // 3: n }; } void M3((string? s1, string? s2)? n) { _ = n switch { ({}, _) => n.Value.s1.ToString(), (_, _) => n.Value.s1.ToString(), // 4: n.Value.s1 _ => n.Value.ToString(), // 5: n }; } void M4((string? s1, string? s2)? n) { _ = n switch { (null, _) => n.Value.s2.ToString(), // 6: n.Value.s2 (_, null) => n.Value.s1.ToString(), (_, _) => n.Value.s1.ToString() + n.Value.s2.ToString(), _ => n.Value.ToString(), // 7: n }; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,22): warning CS8629: Nullable value type may be null. // var q => n.Value.ToString(), // 1: n Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "n").WithLocation(7, 22), // (13,23): warning CS8602: Dereference of a possibly null reference. // (_, _) => n.Value.s1.ToString(), // 2: n.Value.s1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Value.s1").WithLocation(13, 23), // (14,23): warning CS8629: Nullable value type may be null. // _ => n.Value.ToString(), // 3: n Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "n").WithLocation(14, 23), // (21,24): warning CS8602: Dereference of a possibly null reference. // (_, _) => n.Value.s1.ToString(), // 4: n.Value.s1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Value.s1").WithLocation(21, 24), // (22,24): warning CS8629: Nullable value type may be null. // _ => n.Value.ToString(), // 5: n Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "n").WithLocation(22, 24), // (28,26): warning CS8602: Dereference of a possibly null reference. // (null, _) => n.Value.s2.ToString(), // 6: n.Value.s2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Value.s2").WithLocation(28, 26), // (31,26): warning CS8629: Nullable value type may be null. // _ => n.Value.ToString(), // 7: n Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "n").WithLocation(31, 26)); } [Fact] [WorkItem(34246, "https://github.com/dotnet/roslyn/issues/34246")] public void LearnFromConstantPattern_01() { var source = @" class Program { static void M(string? s) { switch (s?.Length) { case 0: s.ToString(); break; } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(34233, "https://github.com/dotnet/roslyn/issues/34233")] [WorkItem(39888, "https://github.com/dotnet/roslyn/issues/39888")] public void SwitchExpressionResultType_01() { CSharpCompilation c = CreateNullableCompilation(@" class Test { void Test1(int i, object? x, object y) { _ = i switch { 1 => x, _ => y }/*T:object?*/; _ = i switch { 1 when x != null => x, _ => y }/*T:object!*/; _ = i switch { 1 => y, _ => x }/*T:object?*/; _ = i switch { 1 => x!, _ => y }/*T:object!*/; _ = i switch { 1 => y, _ => x! }/*T:object!*/; } void Test2(int i, C x, D y) { _ = i switch { 2 => x, _ => y }/*T:D?*/; _ = i switch { 2 => y, _ => x }/*T:D?*/; } void Test3(int i, IIn<string> x, IIn<object>? y) { _ = i switch { 3 => x, _ => y }/*T:IIn<string!>?*/; _ = i switch { 3 => y, _ => x }/*T:IIn<string!>?*/; } void Test4(int i, IOut<string> x, IOut<object>? y) { _ = i switch { 4 => x, _ => y }/*T:IOut<object!>?*/; _ = i switch { 4 => y, _ => x }/*T:IOut<object!>?*/; } void Test5(int i, I<string> x, I<object>? y) { _ = i switch { 5 => x, _ => y }/*T:!*//*CT:!*/; // 1 _ = i switch { 5 => y, _ => x }/*T:!*//*CT:!*/; // 2 } void Test6(int i, I<string> x, I<string?> y) { _ = i switch { 6 => x, _ => y }/*T:I<string!>!*/; // 3 _ = i switch { 6 => y, _ => x }/*T:I<string!>!*/; // 4 } void Test7<T>(int i, T x) { _ = i switch { 7 => x, _ => default }/*T:T*/; _ = i switch { 7 => default, _ => x }/*T:T*/; } } class B { public static implicit operator D?(B? b) => throw null!; } class C : B {} class D {} public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "); c.VerifyTypes(); c.VerifyDiagnostics( // (33,15): error CS8506: No best type was found for the switch expression. // _ = i switch { 5 => x, _ => y }/*T:<null>!*//*CT:!*/; // 1 Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(33, 15), // (34,15): error CS8506: No best type was found for the switch expression. // _ = i switch { 5 => y, _ => x }/*T:<null>!*//*CT:!*/; // 2 Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(34, 15), // (39,37): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<string>'. // _ = i switch { 6 => x, _ => y }/*T:I<string!>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<string?>", "I<string>").WithLocation(39, 37), // (40,29): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<string>'. // _ = i switch { 6 => y, _ => x }/*T:I<string!>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<string?>", "I<string>").WithLocation(40, 29) ); } [Fact] [WorkItem(39264, "https://github.com/dotnet/roslyn/issues/39264")] public void IsPatternSplitState_01() { CSharpCompilation c = CreateNullableCompilation(@" #nullable enable class C { string? field = string.Empty; string? otherField = string.Empty; void M1(C c) { if (c.field == null) return; c.field.ToString(); } void M2(C c) { if (c is { field: null }) return; c.field.ToString(); } void M3(C c) { switch (c) { case { field: null }: break; default: c.field.ToString(); break; } } void M4(C c) { _ = c switch { { field: null } => string.Empty, _ => c.field.ToString(), }; } void M5(C c) { if (c is { field: null }) return; c.otherField.ToString(); // W } } "); c.VerifyDiagnostics( // (47,9): warning CS8602: Dereference of a possibly null reference. // c.otherField.ToString(); // W Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.otherField").WithLocation(47, 9) ); } [Fact] [WorkItem(39264, "https://github.com/dotnet/roslyn/issues/39264")] public void IsPatternSplitState_02() { CSharpCompilation c = CreateNullableCompilation(@" #nullable enable class C { C? c = null; void M1(C c) { if (c is { c: null }) { if (c.c != null) { c.c.c.c.ToString(); } } } } "); c.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // c.c.c.c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.c.c").WithLocation(13, 17), // (13,17): warning CS8602: Dereference of a possibly null reference. // c.c.c.c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.c.c.c").WithLocation(13, 17)); } [Fact] [WorkItem(39264, "https://github.com/dotnet/roslyn/issues/39264")] public void IsPatternSplitState_03() { CSharpCompilation c = CreateNullableCompilation(@" #nullable enable public class C { C? c = null; public static void Main() { C c = new C(); M1(c, new C()); } static void M1(C c, C c2) { if (c is { c : null } && c2 is { c: null }) { c.c = c2; if (c.c != null) { c.c.c.ToString(); // warning } } } } "); c.VerifyDiagnostics( // (19,17): warning CS8602: Dereference of a possibly null reference. // c.c.c.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.c.c").WithLocation(19, 17) ); } [Fact] [WorkItem(40629, "https://github.com/dotnet/roslyn/issues/40629")] public void NullTestInSwitch_01() { CSharpCompilation c = CreateNullableCompilation(@" #nullable enable class C { void M(object? p) { switch (p) { case null: return; } p.ToString(); } } "); c.VerifyDiagnostics(); } [Fact] public void NotNullIsAPureNullTest() { var source = @"#nullable enable class C { void M1(C? x) { if (x is not null) x.ToString(); x.ToString(); // 1 } void M2(C x) { if (x is not null) x.ToString(); x.ToString(); // 2 } void M3(C x) { if (x is not null or _) x.ToString(); // 3 x.ToString(); } void M4(C x) { if (x is null or _) x.ToString(); // 4 x.ToString(); } void M5(C x) { if (x is _ or not null) x.ToString(); // 5 x.ToString(); } void M6(C x) { if (x is _ or null) x.ToString(); // 6 x.ToString(); } void M7(C x) { if (x is _ and null) x.ToString(); // 7 x.ToString(); } void M8(C x) { if (x is _ and not null) x.ToString(); x.ToString(); // 8 } void M9(C x) { if (x is not null and _) x.ToString(); x.ToString(); // 9 } void M10(int? x) { if (x is < 0) x.Value.ToString(); x.Value.ToString(); // 10 } void M11(C x) { if (x is not object) x.ToString(); // 11 else x.ToString(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 9), // (18,13): warning CS8794: An expression of type 'C' always matches the provided pattern. // if (x is not null or _) Diagnostic(ErrorCode.WRN_IsPatternAlways, "x is not null or _").WithArguments("C").WithLocation(18, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(19, 13), // (24,13): warning CS8794: An expression of type 'C' always matches the provided pattern. // if (x is null or _) Diagnostic(ErrorCode.WRN_IsPatternAlways, "x is null or _").WithArguments("C").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(25, 13), // (30,13): warning CS8794: An expression of type 'C' always matches the provided pattern. // if (x is _ or not null) Diagnostic(ErrorCode.WRN_IsPatternAlways, "x is _ or not null").WithArguments("C").WithLocation(30, 13), // (31,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 13), // (36,13): warning CS8794: An expression of type 'C' always matches the provided pattern. // if (x is _ or null) Diagnostic(ErrorCode.WRN_IsPatternAlways, "x is _ or null").WithArguments("C").WithLocation(36, 13), // (37,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(37, 13), // (43,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(43, 13), // (50,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(50, 9), // (56,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(56, 9), // (62,9): warning CS8629: Nullable value type may be null. // x.Value.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(62, 9), // (67,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(67, 13) ); } [Fact] [WorkItem(50161, "https://github.com/dotnet/roslyn/issues/50161")] public void NestedPattern_Field_01() { var source = @"#nullable enable class E { public E F = new E(); } class Test { static void M(E e) { switch (e) { case { F: { F: { F: { F: null } } } }: break; } e.F.F.F.F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // e.F.F.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F.F.F.F").WithLocation(14, 9)); } [Fact] [WorkItem(50161, "https://github.com/dotnet/roslyn/issues/50161")] public void NestedPattern_Field_02() { var source = @"#nullable enable class E { public E F = new E(); } class Test { static void M(E e) { switch (e) { case { F: { F: { F: { F: { F: null } } } } }: break; } e.F.F.F.F.F.ToString(); } }"; // No warning because MaxSlotDepth exceeded. var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(50161, "https://github.com/dotnet/roslyn/issues/50161")] public void NestedPattern_Property_01() { var source = @"#nullable enable class E { public E P => new E(); } class Test { static void M(E e) { switch (e) { case { P: { P: { P: { P: null } } } }: break; } e.P.P.P.P.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // e.P.P.P.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.P.P.P.P").WithLocation(14, 9)); } [Fact] [WorkItem(50161, "https://github.com/dotnet/roslyn/issues/50161")] public void NestedPattern_Property_02() { var source = @"#nullable enable class E { public E P => new E(); } class Test { static void M(E e) { switch (e) { case { P: { P: { P: { P: { P: null } } } } }: break; } e.P.P.P.P.P.ToString(); } }"; // No warning because MaxSlotDepth exceeded. var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void NestedLambdaArm_DoesNotObserveStateFromOtherArms() { var comp = CreateCompilation(@" using System; class C { public void M(object? o, Action? action) { _ = o switch { null => () => { action(); }, _ => action = new Action(() => {}), }; } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): warning CS8602: Dereference of a possibly null reference. // null => () => { action(); }, Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "action").WithLocation(8, 29) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_01() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s = null; Func<string> a = b switch { true => () => s.ToString(), false => () => s?.ToString() }; } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,51): warning CS8602: Dereference of a possibly null reference. // Func<string> a = b switch { true => () => s.ToString(), false => () => s?.ToString() }; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 51), // (8,80): warning CS8603: Possible null reference return. // Func<string> a = b switch { true => () => s.ToString(), false => () => s?.ToString() }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s?.ToString()").WithLocation(8, 80) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_02() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s = null; var a = (Func<string>)(b switch { true => () => s.ToString(), false => () => s?.ToString() }); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,57): warning CS8602: Dereference of a possibly null reference. // var a = (Func<string>)(b switch { true => () => s.ToString(), false => () => s?.ToString() }); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 57), // (8,86): warning CS8603: Possible null reference return. // var a = (Func<string>)(b switch { true => () => s.ToString(), false => () => s?.ToString() }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s?.ToString()").WithLocation(8, 86) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_03() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { Func<string>? s = () => """"; Func<object>? a = (b switch { true => s = null, false => () => s() }); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_04() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { Func<string>? s = () => """"; Func<object>? a = (b switch { true => () => s(), false => s = null }); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_05() { var source = @"#nullable enable class C { static void M(bool b) { string? s = null; object a = b switch { true => () => s.ToString(), false => () => s?.ToString() }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,21): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // true => () => s.ToString(), Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => s.ToString()").WithArguments("lambda expression", "object").WithLocation(9, 21), // (9,27): warning CS8602: Dereference of a possibly null reference. // true => () => s.ToString(), Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 27), // (10,22): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // false => () => s?.ToString() Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => s?.ToString()").WithArguments("lambda expression", "object").WithLocation(10, 22)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,27): warning CS8602: Dereference of a possibly null reference. // true => () => s.ToString(), Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 27)); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_06() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s1 = null; string? s2 = """"; M1(s2, b switch { true => () => s1.ToString(), false => () => s1?.ToString() }).ToString(); } static T M1<T>(T t1, Func<T> t2) => t1; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,34): warning CS8602: Dereference of a possibly null reference. // true => () => s1.ToString(), Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(11, 34), // (12,35): warning CS8603: Possible null reference return. // false => () => s1?.ToString() Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s1?.ToString()").WithLocation(12, 35) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_07() { var comp = CreateCompilation(@" interface I {} class A : I {} class B : I {} class C { static void M(I i, A a, B? b, bool @bool) { M1(i, @bool switch { true => a, false => b }).ToString(); } static T M1<T>(T t1, T t2) => t1; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): warning CS8604: Possible null reference argument for parameter 't2' in 'I C.M1<I>(I t1, I t2)'. // M1(i, @bool switch { true => a, false => b }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "@bool switch { true => a, false => b }").WithArguments("t2", "I C.M1<I>(I t1, I t2)").WithLocation(9, 15) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void TargetTypedSwitch_08() { var comp = CreateCompilation(@" C? c = """".Length switch { > 0 => new A(), _ => new B() }; c.ToString(); class C { } class A { public static implicit operator C?(A a) => null; } class B { public static implicit operator C?(B b) => null; } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,1): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(3, 1) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void TargetTypedSwitch_09() { var comp = CreateCompilation(@" C? c = true switch { true => new A(), false => new B() }; c.ToString(); class C { } class A { public static implicit operator C(A a) => new C(); } class B { public static implicit operator C?(B b) => null; } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void TargetTypedSwitch_10() { var comp = CreateCompilation(@" C? c = false switch { true => new A(), false => new B() }; c.ToString(); class C { } class A { public static implicit operator C?(A a) => null; } class B { public static implicit operator C(B b) => new C(); } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.NullableReferenceTypes, CompilerFeature.Patterns)] public class NullableReferenceTypesVsPatterns : CSharpTestBase { private CSharpCompilation CreateNullableCompilation(string source) { return CreateCompilation(new[] { source }, options: WithNullableEnable()); } [Fact] public void VarPatternInfersNullableType() { CSharpCompilation c = CreateNullableCompilation(@" public class C { public string Field = null!; void M1() { if (this is { Field: var s }) { s.ToString(); s = null; } } void M2() { if (this is (var s) _) { s.ToString(); s = null; } } void Deconstruct(out string s) => throw null!; } "); c.VerifyDiagnostics(); } [Fact] public void ConditionalBranching_IsConstantPattern_Null() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { if (x is null) { x.ToString(); // warn } else { x.ToString(); } } } "); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_NullInverted() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { if (!(x is null)) { x.ToString(); } else { x.ToString(); // warn } } } "); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_NonNull() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { const string nonNullConstant = ""hello""; if (x is nonNullConstant) { x.ToString(); } else { x.ToString(); // warn } } } "); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_NullConstant() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { const string? nullConstant = null; if (x is nullConstant) { x.ToString(); // warn } else { x.ToString(); } } } "); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_NonConstant() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { string nonConstant = ""hello""; if (x is nonConstant) { x.ToString(); } } } "); c.VerifyDiagnostics( // (7,18): error CS0150: A constant value is expected // if (x is nonConstant) Diagnostic(ErrorCode.ERR_ConstantExpected, "nonConstant").WithLocation(7, 18), // (9,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 13) ); } [Fact] public void ConditionalBranching_IsConstantPattern_Null_AlreadyTestedAsNonNull() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { if (x != null) { if (x is null) { x.ToString(); // warn } else { x.ToString(); } } } } "); c.VerifyDiagnostics( // (10,17): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 17) ); } [Fact] public void ConditionalBranching_IsConstantPattern_Null_AlreadyTestedAsNull() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test(object? x) { if (x == null) { if (x is null) { x.ToString(); // warn } else { x.ToString(); } } } } "); c.VerifyDiagnostics( // (10,17): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 17) ); } [Fact] public void ConditionalBranching_IsDeclarationPattern_02() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { if (x is C c) { x.ToString(); c.ToString(); } else { x.ToString(); // warn } } void Test2(object x) { if (x is C c) { x.ToString(); c.ToString(); } else { x.ToString(); } } } "); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13) ); } [Fact] public void ConditionalBranching_IsVarDeclarationPattern() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { if (x is var c) { x.ToString(); // warn 1 c /*T:object?*/ .ToString(); // warn 2 c = null; } else { x.ToString(); } } void Test2(object x) { if (x is var c) { x.ToString(); c /*T:object!*/ .ToString(); } else { x.ToString(); } } } "); c.VerifyTypes(); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // c /*T:object?*/ .ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 13) ); } [Fact] public void ConditionalBranching_IsVarDeclarationPattern_Discard() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { if (x is var _) { x.ToString(); // 1 } else { x.ToString(); } } void Test2(object x) { if (x is var _) { x.ToString(); } else { x.ToString(); } } } "); c.VerifyTypes(); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13) ); } [Fact] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void ConditionalBranching_IsVarDeclarationPattern_AlreadyTestedAsNonNull() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { if (x != null) { if (x is var c) { c /*T:object!*/ .ToString(); c = null; } } } void Test2(object x) { if (x != null) { if (x is var c) { c /*T:object!*/ .ToString(); c = null; } } } } "); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void IsPattern_01() { var source = @"class C { static void F(object x) { } static void G(string s) { F(s is var o); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29909, "https://github.com/dotnet/roslyn/issues/29909")] public void IsPattern_02() { var source = @"class C { static void F(string s) { } static void G(string? s) { if (s is string t) { F(t); F(s); } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void IsPattern_AffectsNullConditionalOperator_DeclarationPattern() { var source = @"class C { static void G1(string? s) { if (s?.ToString() is string t) { s.ToString(); } else { s.ToString(); // 1 } } static void G2(string s) { if (s?.ToString() is string t) { s.ToString(); } else { s.ToString(); // 2 } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(11, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(22, 13)); } [Fact] public void IsPattern_AffectsNullConditionalOperator_NullableValueType() { var source = @"class C { static void G1(int? i) { if (i?.ToString() is string t) { i.Value.ToString(); } else { i.Value.ToString(); // 1 } } static void G2(int? i) { i = 1; if (i?.ToString() is string t) { i.Value.ToString(); } else { i.Value.ToString(); // 2 } } static void G3(int? i) { i = 1; if (i is int q) { i.Value.ToString(); } else { i.Value.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // i.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(11, 13), // (23,13): warning CS8629: Nullable value type may be null. // i.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(23, 13)); } [Fact] public void IsPattern_AffectsNullConditionalOperator_NullableValueType_Nested() { var source = @" public struct S { public int? field; } class C { static void G(S? s) { if (s?.field?.ToString() is string t) { s.Value.ToString(); s.Value.field.Value.ToString(); } else { s.Value.ToString(); // warn s.Value.field.Value.ToString(); // warn } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (17,13): warning CS8629: Nullable value type may be null. // s.Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s").WithLocation(17, 13), // (18,13): warning CS8629: Nullable value type may be null. // s.Value.field.Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s.Value.field").WithLocation(18, 13) ); } [Fact, WorkItem(28798, "https://github.com/dotnet/roslyn/issues/28798")] public void IsPattern_AffectsNullConditionalOperator_VarPattern() { var source = @"class C { static void G(string? s) { if (s?.ToString() is var t) { s.ToString(); // 1 } else { s.ToString(); } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13) ); } [Fact] public void IsPattern_AffectsNullConditionalOperator_NullConstantPattern() { var source = @"class C { static void G(string? s) { if (s?.ToString() is null) { s.ToString(); // warn } else { s.ToString(); } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13) ); } [Fact] [WorkItem(29909, "https://github.com/dotnet/roslyn/issues/29909")] [WorkItem(23944, "https://github.com/dotnet/roslyn/issues/23944")] public void PatternSwitch() { var source = @"class C { static void F(object o) { } static void G(object? x) { switch (x) { case string s: F(s); F(x); break; case object y when y is string t: F(y); F(t); F(x); break; case null: F(x); // 1 break; default: F(x); break; } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (18,19): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // F(x); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "void C.F(object o)").WithLocation(18, 19)); } [Fact] public void IsDeclarationPattern_01() { var source = @"class Program { static void F1(object x1) { if (x1 is string y1) { x1/*T:object!*/.ToString(); y1/*T:string!*/.ToString(); } x1/*T:object!*/.ToString(); } static void F2(object? x2) { if (x2 is string y2) { x2/*T:object!*/.ToString(); y2/*T:string!*/.ToString(); } x2/*T:object?*/.ToString(); // 1 } static void F3(object x3) { x3 = null; // 2 if (x3 is string y3) { x3/*T:object!*/.ToString(); y3/*T:string!*/.ToString(); } x3/*T:object?*/.ToString(); // 3 } static void F4(object? x4) { if (x4 == null) return; if (x4 is string y4) { x4/*T:object!*/.ToString(); y4/*T:string!*/.ToString(); } x4/*T:object!*/.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(19, 9), // (23,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(23, 14), // (29,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(29, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(30952, "https://github.com/dotnet/roslyn/issues/30952")] public void IsDeclarationPattern_02() { var source = @"class Program { static void F1<T, U>(T t1) where T : class where U : class { if (t1 is U u1) { t1.ToString(); u1.ToString(); } t1.ToString(); } static void F2<T, U>(T t2) where T : class? where U : class { if (t2 is U u2) { t2.ToString(); u2.ToString(); } t2.ToString(); // 1 } static void F3<T, U>(T t3) where T : class where U : class { t3 = null; // 2 if (t3 is U u3) { t3.ToString(); u3.ToString(); } t3.ToString(); // 3 } static void F4<T, U>(T t4) where T : class? where U : class { if (t4 == null) return; if (t4 is U u4) { t4.ToString(); u4.ToString(); } t4.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (23,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(23, 9), // (29,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t3 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(29, 14), // (35,9): warning CS8602: Dereference of a possibly null reference. // t3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(35, 9)); } [Fact] public void IsDeclarationPattern_03() { var source = @"class Program { static void F1<T, U>(T t1) { if (t1 is U u1) { t1.ToString(); u1.ToString(); } t1.ToString(); // 1 } static void F2<T, U>(T t2) { if (t2 == null) return; if (t2 is U u2) { t2.ToString(); u2.ToString(); } t2.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(10, 9)); } [Fact] public void IsDeclarationPattern_NeverNull_01() { var source = @"class Program { static void F1(object x1) { if (x1 is string y1) { x1.ToString(); x1?.ToString(); y1.ToString(); y1?.ToString(); } x1.ToString(); // 1 (because of x1?. above) } static void F2(object? x2) { if (x2 is string y2) { x2.ToString(); x2?.ToString(); y2.ToString(); y2?.ToString(); } x2.ToString(); // 2 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 (because of x1?. above) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(23, 9)); } [Fact] public void IsDeclarationPattern_Unassigned_01() { var source = @"class Program { static void F1(object x1) { if (x1 is string y1) { } else { x1.ToString(); y1.ToString(); // 1 } } static void F2(object? x2) { if (x2 is string y2) { } else { x2.ToString(); // 2 y2.ToString(); // 3 } } static void F3(object x3) { x3 = null; // 4 if (x3 is string y3) { } else { x3.ToString(); // 5 y3.ToString(); // 6 } } static void F4(object? x4) { if (x4 == null) return; if (x4 is string y4) { } else { x4.ToString(); y4.ToString(); // 7 } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): error CS0165: Use of unassigned local variable 'y1' // y1.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(11, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(21, 13), // (22,13): error CS0165: Use of unassigned local variable 'y2' // y2.ToString(); // 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "y2").WithArguments("y2").WithLocation(22, 13), // (27,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(27, 14), // (33,13): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(33, 13), // (34,13): error CS0165: Use of unassigned local variable 'y3' // y3.ToString(); // 6 Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(34, 13), // (46,13): error CS0165: Use of unassigned local variable 'y4' // y4.ToString(); // 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "y4").WithArguments("y4").WithLocation(46, 13)); } [Fact] public void IsDeclarationPattern_Unassigned_02() { var source = @"class Program { static void F1(object x1) { if (x1 is string y1) { } x1.ToString(); y1.ToString(); // 1 } static void F2(object? x2) { if (x2 is string y2) { } x2.ToString(); // 2 y2.ToString(); // 3 } static void F3(object x3) { x3 = null; // 4 if (x3 is string y3) { } x3.ToString(); // 5 y3.ToString(); // 6 } static void F4(object? x4) { if (x4 == null) return; if (x4 is string y4) { } x4.ToString(); y4.ToString(); // 7 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0165: Use of unassigned local variable 'y1' // y1.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(7, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(12, 9), // (13,9): error CS0165: Use of unassigned local variable 'y2' // y2.ToString(); // 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "y2").WithArguments("y2").WithLocation(13, 9), // (17,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(17, 14), // (19,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(19, 9), // (20,9): error CS0165: Use of unassigned local variable 'y3' // y3.ToString(); // 6 Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(20, 9), // (27,9): error CS0165: Use of unassigned local variable 'y4' // y4.ToString(); // 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "y4").WithArguments("y4").WithLocation(27, 9)); } [Fact] public void UnconstrainedTypeParameter_PatternMatching() { var source = @" class C { static void F1<T>(object o, T tin) { if (o is T t1) { t1.ToString(); } else { t1 = default; } t1.ToString(); // 1 if (!(o is T t2)) { t2 = tin; } else { t2.ToString(); } t2.ToString(); // 2 if (!(o is T t3)) return; t3.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(15, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(25, 9) ); } [WorkItem(32503, "https://github.com/dotnet/roslyn/issues/32503")] [Fact] public void PatternDeclarationBreaksNullableAnalysis() { var source = @" class A { } class B : A { A M() { var s = new A(); if (s is B b) {} return s; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void InferenceWithITuplePattern() { var source = @" class A { } class B : A { A M() { var s = new A(); if (s is B b) {} return s; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void RecursivePatternNullInferenceWithDowncast_01() { var source = @" class Base { public object Value = """"; } class Derived : Base { public new object Value = """"; } class Program { void M(Base? b) { if (b is Derived { Value: null }) b.Value.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void RecursivePatternNullInferenceWithDowncast_02() { var source = @" class Base { public object Value = """"; } class Derived : Base { } class Program { void M(Base? b) { if (b is Derived { Value: null }) b.Value.ToString(); // 1 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Value").WithLocation(14, 13)); } [Fact] public void TuplePatternNullInference_01() { var source = @" class Program { void M((object, object) t) { if (t is (1, null)) { } else { t.Item2.ToString(); // 1 t.Item1.ToString(); } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(11, 13)); } [Fact] public void MultiplePathsThroughDecisionDag_01() { var source = @" class Program { bool M1(object? o, bool cond = true) { o = 1; switch (o) { case null: throw null!; case """" when M1(o = null): break; default: if (cond) o.ToString(); // 1 break; } return cond; } bool M2(object? o, bool cond = true) { o = 1; switch (o) { case """" when M2(o = null): break; default: if (cond) o.ToString(); // 2 break; } return cond; } bool M3(object? o, bool cond = true) { o = 1; switch (o) { case null: throw null!; default: if (cond) o.ToString(); break; } return cond; } bool M4(object? o, bool cond = true) { o = 1; switch (o) { case null: throw null!; case """" when M4(o = null): break; case var q: q.ToString(); // 3 (!?) break; } return cond; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (14,27): warning CS8602: Dereference of a possibly null reference. // if (cond) o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(14, 27), // (28,27): warning CS8602: Dereference of a possibly null reference. // if (cond) o.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(28, 27), // (58,17): warning CS8602: Dereference of a possibly null reference. // q.ToString(); // 3 (!?) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "q").WithLocation(58, 17)); } [Fact] [WorkItem(30597, "https://github.com/dotnet/roslyn/issues/30597")] [WorkItem(32414, "https://github.com/dotnet/roslyn/issues/32414")] public void NotExhaustiveForNull_01() { var source = @" class Program { void M0(object o) { var t = (o, o); _ = t switch { (null, null) => 1, (null, {}) => 2, ({}, null) => 3, ({}, {}) => 4, }; } void M1(object o) { var t = (o, o); _ = t switch // 1 not exhaustive { (null, 2) => 1, ({}, {}) => 2, }; } void M2(object o) { var t = (o, o); _ = t switch // 2 not exhaustive { (1, 2) => 1, ({}, {}) => 2, }; } void M3(object o) { var t = (o, o); _ = t switch // 3 not exhaustive { (null, 2) => 1, ({}, {}) => 2, (null, {}) => 3, }; } void M4(object o) { var t = (o, o); _ = t switch // 4 not exhaustive { { Item1: null, Item2: 2 } => 1, { Item1: {}, Item2: {} } => 2, }; } void M5(object o) { var t = (o, o); _ = t switch // 5 not exhaustive { { Item1: 1, Item2: 2 } => 1, { Item1: {}, Item2: {} } => 2, }; } void M6(object o) { var t = (o, o); _ = t switch // 6 not exhaustive { { Item1: null, Item2: 2 } => 1, { Item1: {}, Item2: {} } => 2, { Item1: null, Item2: {} } => 3, }; } void M7(object o, bool b) { _ = o switch // 7 not exhaustive { null when b => 1, {} => 2, }; } void M8(object o, bool b) { _ = o switch { null when b => 1, {} => 2, null => 3, }; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (18,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // _ = t switch // 1 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(18, 15), // (27,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // _ = t switch // 2 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(27, 15), // (36,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(not null, null)' is not covered. // _ = t switch // 3 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(not null, null)").WithLocation(36, 15), // (46,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // _ = t switch // 4 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(46, 15), // (55,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // _ = t switch // 5 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(55, 15), // (64,15): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(not null, null)' is not covered. // _ = t switch // 6 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(not null, null)").WithLocation(64, 15), // (73,15): warning CS8847: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern 'null' is not covered. However, a pattern with a 'when' clause might successfully match this value. // _ = o switch // 7 not exhaustive Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen, "switch").WithArguments("null").WithLocation(73, 15)); } [Fact] [WorkItem(30597, "https://github.com/dotnet/roslyn/issues/30597")] [WorkItem(32414, "https://github.com/dotnet/roslyn/issues/32414")] public void NotExhaustiveForNull_02() { var source = @" class Test { int M1(string s1, string s2) { return (s1, s2) switch { (string x, string y) => x.Length + y.Length }; } int M2(string? s1, string s2) { return (s1, s2) switch { // 1 (string x, string y) => x.Length + y.Length }; } int M3(string s1, string? s2) { return (s1, s2) switch { // 2 (string x, string y) => x.Length + y.Length }; } int M4(string? s1, string? s2) { return (s1, s2) switch { // 3 (string x, string y) => x.Length + y.Length }; } int M5(string s1, string s2) { return (s1, s2) switch { // 4 (null, ""x"") => 1, (string x, string y) => x.Length + y.Length }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (12,25): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // return (s1, s2) switch { // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(12, 25), // (18,25): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // return (s1, s2) switch { // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(18, 25), // (24,25): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, _)' is not covered. // return (s1, s2) switch { // 3 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, _)").WithLocation(24, 25), // (30,25): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(null, "")' is not covered. // return (s1, s2) switch { // 4 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(null, \"\")").WithLocation(30, 25)); } [Fact, WorkItem(31881, "https://github.com/dotnet/roslyn/issues/31881")] public void NullableVsPattern_31881() { var source = @" using System; public class C { public object? AProperty { get; set; } public void M(C? input, int i) { if (input?.AProperty is string str) { Console.WriteLine(str.ToString()); switch (i) { case 1: Console.WriteLine(input?.AProperty.ToString()); break; case 2: Console.WriteLine(input.AProperty.ToString()); break; case 3: Console.WriteLine(input.ToString()); break; } } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(33499, "https://github.com/dotnet/roslyn/issues/33499")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void PatternVariablesAreNotOblivious_33499() { var source = @" class Test { static void M(object o) { if (o is string s) { } s = null; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 13) ); } [Fact] public void IsPatternAlwaysFalse() { var source = @" class Test { void M1(ref object o) { if (2 is 3) o = null; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (6,13): warning CS8519: The given expression never matches the provided pattern. // if (2 is 3) Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "2 is 3").WithLocation(6, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructWithNotBackedProperty() { var source = @" struct Point { public object X, Y; public Point Mirror => new Point { X = Y, Y = X }; bool Test => this is { X: 1, Y: 2, Mirror: { X: 2, Y: 1 } }; }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void LearnFromNullPattern_01() { var source = @" class Node { public Node Next = null!; } class Program { void M1(Node n) { if (n is null) {} n.Next.Next.Next.ToString(); // 1 } void M2(Node n) { if (n is {Next: null}) {} n.Next.Next.Next.ToString(); // 2 } void M3(Node n) { if (n is {Next: {Next: null}}) {} n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(16, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(21, 9)); } [Fact] public void LearnFromNullPattern_02() { var source = @" class Node { public Node Next = null!; } class Program { void M1(Node n) { switch (n) { case null: break; } n.Next.Next.Next.ToString(); // 1 } void M2(Node n) { switch (n) { case {Next: null}: break; } n.Next.Next.Next.ToString(); // 2 } void M3(Node n) { switch (n) { case {Next: {Next: null}}: break; } n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(16, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(21, 9)); } [Fact] public void LearnFromNullPattern_03() { var source = @" class Node { public Node Next = null!; } class Program { void M1(Node n) { _ = n switch { null => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 1 } void M2(Node n) { _ = n switch { {Next: null} => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 2 } void M3(Node n) { _ = n switch { {Next: {Next: null}} => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(16, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(21, 9)); } [Fact] public void LearnFromNullPattern_04() { var source = @" #nullable disable class Node { public Node Next = null!; } #nullable enable class Program { #nullable disable void M1(Node n) #nullable enable { _ = n switch { null => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 1 } #nullable disable void M2(Node n) #nullable enable { _ = n switch { {Next: null} => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 2 } #nullable disable void M3(Node n) #nullable enable { _ = n switch { {Next: {Next: null}} => 1, _ => 2 }; n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n").WithLocation(15, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(22, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(29, 9)); } [Fact] public void LearnFromNullPattern_05() { var source = @" class Program { void M1((string s1, string s2) n) { _ = n switch { (_, null) => n.s1.ToString(), var q => n.s1.ToString(), }; n.s1.ToString(); n.s2.ToString(); // 1 } void M2((string s1, string s2) n) { _ = n switch { (null, _) => n.s1.ToString(), // 2 (_, _) => n.s1.ToString(), }; n.s1.ToString(); // 3 n.s2.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // n.s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.s2").WithLocation(11, 9), // (16,26): warning CS8602: Dereference of a possibly null reference. // (null, _) => n.s1.ToString(), // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.s1").WithLocation(16, 26)); } [Fact] public void LearnFromNonNullPattern_01() { var source = @" class Node { public Node? Next = null; } class Program { void M1(Node? n) { if (n is {} q) n.Next.ToString(); // 1 } void M2(Node? n) { if (n is {Next: {}} q) n.Next.Next.ToString(); // 2 } void M3(Node? n) { if (n is {Next: {Next: {}}} q) n.Next.Next.Next.ToString(); // 3 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // n.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(11, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(16, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next.Next").WithLocation(21, 13)); } [Fact] public void LearnFromNonNullPattern_02() { var source = @" class Node { public Node? Next = null; } class Program { void M1(Node? n) { switch (n) { case {} q: n.Next.ToString(); // 1 break; } } void M2(Node? n) { switch (n) { case {Next: {}} q: n.Next.Next.ToString(); // 2 break; } } void M3(Node? n) { switch (n) { case {Next: {Next: {}}} q: n.Next.Next.Next.ToString(); // 3 break; } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // n.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(11, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(17, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next.Next").WithLocation(23, 13)); } [Fact] public void LearnFromNonNullPattern_03() { var source = @" class Node { public Node? Next = null; } class Program { void M1(Node? n) { _ = n switch { {} q => n.Next.ToString(), // 1 _ => string.Empty }; } void M2(Node? n) { _ = n switch { {Next: {}} q => n.Next.Next.ToString(), // 2 _ => string.Empty }; } void M3(Node? n) { _ = n switch { {Next: {Next: {}}} q => n.Next.Next.Next.ToString(), // 3 _ => string.Empty }; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // n.Next.ToString(), // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next").WithLocation(11, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.ToString(), // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next").WithLocation(17, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // n.Next.Next.Next.ToString(), // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Next.Next.Next").WithLocation(23, 13)); } [Fact] public void LearnFromNonNullPattern_04() { var source = @" class Program { void M1((string? s1, string? s2)? n) { _ = n switch { var q => n.Value.ToString(), // 1: n }; } void M2((string? s1, string? s2)? n) { _ = n switch { (_, _) => n.Value.s1.ToString(), // 2: n.Value.s1 _ => n.Value.ToString(), // 3: n }; } void M3((string? s1, string? s2)? n) { _ = n switch { ({}, _) => n.Value.s1.ToString(), (_, _) => n.Value.s1.ToString(), // 4: n.Value.s1 _ => n.Value.ToString(), // 5: n }; } void M4((string? s1, string? s2)? n) { _ = n switch { (null, _) => n.Value.s2.ToString(), // 6: n.Value.s2 (_, null) => n.Value.s1.ToString(), (_, _) => n.Value.s1.ToString() + n.Value.s2.ToString(), _ => n.Value.ToString(), // 7: n }; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,22): warning CS8629: Nullable value type may be null. // var q => n.Value.ToString(), // 1: n Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "n").WithLocation(7, 22), // (13,23): warning CS8602: Dereference of a possibly null reference. // (_, _) => n.Value.s1.ToString(), // 2: n.Value.s1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Value.s1").WithLocation(13, 23), // (14,23): warning CS8629: Nullable value type may be null. // _ => n.Value.ToString(), // 3: n Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "n").WithLocation(14, 23), // (21,24): warning CS8602: Dereference of a possibly null reference. // (_, _) => n.Value.s1.ToString(), // 4: n.Value.s1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Value.s1").WithLocation(21, 24), // (22,24): warning CS8629: Nullable value type may be null. // _ => n.Value.ToString(), // 5: n Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "n").WithLocation(22, 24), // (28,26): warning CS8602: Dereference of a possibly null reference. // (null, _) => n.Value.s2.ToString(), // 6: n.Value.s2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "n.Value.s2").WithLocation(28, 26), // (31,26): warning CS8629: Nullable value type may be null. // _ => n.Value.ToString(), // 7: n Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "n").WithLocation(31, 26)); } [Fact] [WorkItem(34246, "https://github.com/dotnet/roslyn/issues/34246")] public void LearnFromConstantPattern_01() { var source = @" class Program { static void M(string? s) { switch (s?.Length) { case 0: s.ToString(); break; } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(34233, "https://github.com/dotnet/roslyn/issues/34233")] [WorkItem(39888, "https://github.com/dotnet/roslyn/issues/39888")] public void SwitchExpressionResultType_01() { CSharpCompilation c = CreateNullableCompilation(@" class Test { void Test1(int i, object? x, object y) { _ = i switch { 1 => x, _ => y }/*T:object?*/; _ = i switch { 1 when x != null => x, _ => y }/*T:object!*/; _ = i switch { 1 => y, _ => x }/*T:object?*/; _ = i switch { 1 => x!, _ => y }/*T:object!*/; _ = i switch { 1 => y, _ => x! }/*T:object!*/; } void Test2(int i, C x, D y) { _ = i switch { 2 => x, _ => y }/*T:D?*/; _ = i switch { 2 => y, _ => x }/*T:D?*/; } void Test3(int i, IIn<string> x, IIn<object>? y) { _ = i switch { 3 => x, _ => y }/*T:IIn<string!>?*/; _ = i switch { 3 => y, _ => x }/*T:IIn<string!>?*/; } void Test4(int i, IOut<string> x, IOut<object>? y) { _ = i switch { 4 => x, _ => y }/*T:IOut<object!>?*/; _ = i switch { 4 => y, _ => x }/*T:IOut<object!>?*/; } void Test5(int i, I<string> x, I<object>? y) { _ = i switch { 5 => x, _ => y }/*T:!*//*CT:!*/; // 1 _ = i switch { 5 => y, _ => x }/*T:!*//*CT:!*/; // 2 } void Test6(int i, I<string> x, I<string?> y) { _ = i switch { 6 => x, _ => y }/*T:I<string!>!*/; // 3 _ = i switch { 6 => y, _ => x }/*T:I<string!>!*/; // 4 } void Test7<T>(int i, T x) { _ = i switch { 7 => x, _ => default }/*T:T*/; _ = i switch { 7 => default, _ => x }/*T:T*/; } } class B { public static implicit operator D?(B? b) => throw null!; } class C : B {} class D {} public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "); c.VerifyTypes(); c.VerifyDiagnostics( // (33,15): error CS8506: No best type was found for the switch expression. // _ = i switch { 5 => x, _ => y }/*T:<null>!*//*CT:!*/; // 1 Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(33, 15), // (34,15): error CS8506: No best type was found for the switch expression. // _ = i switch { 5 => y, _ => x }/*T:<null>!*//*CT:!*/; // 2 Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(34, 15), // (39,37): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<string>'. // _ = i switch { 6 => x, _ => y }/*T:I<string!>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<string?>", "I<string>").WithLocation(39, 37), // (40,29): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<string>'. // _ = i switch { 6 => y, _ => x }/*T:I<string!>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<string?>", "I<string>").WithLocation(40, 29) ); } [Fact] [WorkItem(39264, "https://github.com/dotnet/roslyn/issues/39264")] public void IsPatternSplitState_01() { CSharpCompilation c = CreateNullableCompilation(@" #nullable enable class C { string? field = string.Empty; string? otherField = string.Empty; void M1(C c) { if (c.field == null) return; c.field.ToString(); } void M2(C c) { if (c is { field: null }) return; c.field.ToString(); } void M3(C c) { switch (c) { case { field: null }: break; default: c.field.ToString(); break; } } void M4(C c) { _ = c switch { { field: null } => string.Empty, _ => c.field.ToString(), }; } void M5(C c) { if (c is { field: null }) return; c.otherField.ToString(); // W } } "); c.VerifyDiagnostics( // (47,9): warning CS8602: Dereference of a possibly null reference. // c.otherField.ToString(); // W Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.otherField").WithLocation(47, 9) ); } [Fact] [WorkItem(39264, "https://github.com/dotnet/roslyn/issues/39264")] public void IsPatternSplitState_02() { CSharpCompilation c = CreateNullableCompilation(@" #nullable enable class C { C? c = null; void M1(C c) { if (c is { c: null }) { if (c.c != null) { c.c.c.c.ToString(); } } } } "); c.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // c.c.c.c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.c.c").WithLocation(13, 17), // (13,17): warning CS8602: Dereference of a possibly null reference. // c.c.c.c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.c.c.c").WithLocation(13, 17)); } [Fact] [WorkItem(39264, "https://github.com/dotnet/roslyn/issues/39264")] public void IsPatternSplitState_03() { CSharpCompilation c = CreateNullableCompilation(@" #nullable enable public class C { C? c = null; public static void Main() { C c = new C(); M1(c, new C()); } static void M1(C c, C c2) { if (c is { c : null } && c2 is { c: null }) { c.c = c2; if (c.c != null) { c.c.c.ToString(); // warning } } } } "); c.VerifyDiagnostics( // (19,17): warning CS8602: Dereference of a possibly null reference. // c.c.c.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.c.c").WithLocation(19, 17) ); } [Fact] [WorkItem(40629, "https://github.com/dotnet/roslyn/issues/40629")] public void NullTestInSwitch_01() { CSharpCompilation c = CreateNullableCompilation(@" #nullable enable class C { void M(object? p) { switch (p) { case null: return; } p.ToString(); } } "); c.VerifyDiagnostics(); } [Fact] public void NotNullIsAPureNullTest() { var source = @"#nullable enable class C { void M1(C? x) { if (x is not null) x.ToString(); x.ToString(); // 1 } void M2(C x) { if (x is not null) x.ToString(); x.ToString(); // 2 } void M3(C x) { if (x is not null or _) x.ToString(); // 3 x.ToString(); } void M4(C x) { if (x is null or _) x.ToString(); // 4 x.ToString(); } void M5(C x) { if (x is _ or not null) x.ToString(); // 5 x.ToString(); } void M6(C x) { if (x is _ or null) x.ToString(); // 6 x.ToString(); } void M7(C x) { if (x is _ and null) x.ToString(); // 7 x.ToString(); } void M8(C x) { if (x is _ and not null) x.ToString(); x.ToString(); // 8 } void M9(C x) { if (x is not null and _) x.ToString(); x.ToString(); // 9 } void M10(int? x) { if (x is < 0) x.Value.ToString(); x.Value.ToString(); // 10 } void M11(C x) { if (x is not object) x.ToString(); // 11 else x.ToString(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 9), // (18,13): warning CS8794: An expression of type 'C' always matches the provided pattern. // if (x is not null or _) Diagnostic(ErrorCode.WRN_IsPatternAlways, "x is not null or _").WithArguments("C").WithLocation(18, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(19, 13), // (24,13): warning CS8794: An expression of type 'C' always matches the provided pattern. // if (x is null or _) Diagnostic(ErrorCode.WRN_IsPatternAlways, "x is null or _").WithArguments("C").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(25, 13), // (30,13): warning CS8794: An expression of type 'C' always matches the provided pattern. // if (x is _ or not null) Diagnostic(ErrorCode.WRN_IsPatternAlways, "x is _ or not null").WithArguments("C").WithLocation(30, 13), // (31,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 13), // (36,13): warning CS8794: An expression of type 'C' always matches the provided pattern. // if (x is _ or null) Diagnostic(ErrorCode.WRN_IsPatternAlways, "x is _ or null").WithArguments("C").WithLocation(36, 13), // (37,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(37, 13), // (43,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(43, 13), // (50,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(50, 9), // (56,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(56, 9), // (62,9): warning CS8629: Nullable value type may be null. // x.Value.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(62, 9), // (67,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(67, 13) ); } [Fact] [WorkItem(50161, "https://github.com/dotnet/roslyn/issues/50161")] public void NestedPattern_Field_01() { var source = @"#nullable enable class E { public E F = new E(); } class Test { static void M(E e) { switch (e) { case { F: { F: { F: { F: null } } } }: break; } e.F.F.F.F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // e.F.F.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F.F.F.F").WithLocation(14, 9)); } [Fact] [WorkItem(50161, "https://github.com/dotnet/roslyn/issues/50161")] public void NestedPattern_Field_02() { var source = @"#nullable enable class E { public E F = new E(); } class Test { static void M(E e) { switch (e) { case { F: { F: { F: { F: { F: null } } } } }: break; } e.F.F.F.F.F.ToString(); } }"; // No warning because MaxSlotDepth exceeded. var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(50161, "https://github.com/dotnet/roslyn/issues/50161")] public void NestedPattern_Property_01() { var source = @"#nullable enable class E { public E P => new E(); } class Test { static void M(E e) { switch (e) { case { P: { P: { P: { P: null } } } }: break; } e.P.P.P.P.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // e.P.P.P.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.P.P.P.P").WithLocation(14, 9)); } [Fact] [WorkItem(50161, "https://github.com/dotnet/roslyn/issues/50161")] public void NestedPattern_Property_02() { var source = @"#nullable enable class E { public E P => new E(); } class Test { static void M(E e) { switch (e) { case { P: { P: { P: { P: { P: null } } } } }: break; } e.P.P.P.P.P.ToString(); } }"; // No warning because MaxSlotDepth exceeded. var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void NestedLambdaArm_DoesNotObserveStateFromOtherArms() { var comp = CreateCompilation(@" using System; class C { public void M(object? o, Action? action) { _ = o switch { null => () => { action(); }, _ => action = new Action(() => {}), }; } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): warning CS8602: Dereference of a possibly null reference. // null => () => { action(); }, Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "action").WithLocation(8, 29) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_01() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s = null; Func<string> a = b switch { true => () => s.ToString(), false => () => s?.ToString() }; } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,51): warning CS8602: Dereference of a possibly null reference. // Func<string> a = b switch { true => () => s.ToString(), false => () => s?.ToString() }; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 51), // (8,80): warning CS8603: Possible null reference return. // Func<string> a = b switch { true => () => s.ToString(), false => () => s?.ToString() }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s?.ToString()").WithLocation(8, 80) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_02() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s = null; var a = (Func<string>)(b switch { true => () => s.ToString(), false => () => s?.ToString() }); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,57): warning CS8602: Dereference of a possibly null reference. // var a = (Func<string>)(b switch { true => () => s.ToString(), false => () => s?.ToString() }); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 57), // (8,86): warning CS8603: Possible null reference return. // var a = (Func<string>)(b switch { true => () => s.ToString(), false => () => s?.ToString() }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s?.ToString()").WithLocation(8, 86) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_03() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { Func<string>? s = () => """"; Func<object>? a = (b switch { true => s = null, false => () => s() }); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_04() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { Func<string>? s = () => """"; Func<object>? a = (b switch { true => () => s(), false => s = null }); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_05() { var source = @"#nullable enable class C { static void M(bool b) { string? s = null; object a = b switch { true => () => s.ToString(), false => () => s?.ToString() }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,21): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // true => () => s.ToString(), Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => s.ToString()").WithArguments("lambda expression", "object").WithLocation(9, 21), // (9,27): warning CS8602: Dereference of a possibly null reference. // true => () => s.ToString(), Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 27), // (10,22): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // false => () => s?.ToString() Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => s?.ToString()").WithArguments("lambda expression", "object").WithLocation(10, 22)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,27): warning CS8602: Dereference of a possibly null reference. // true => () => s.ToString(), Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 27)); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_06() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s1 = null; string? s2 = """"; M1(s2, b switch { true => () => s1.ToString(), false => () => s1?.ToString() }).ToString(); } static T M1<T>(T t1, Func<T> t2) => t1; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,34): warning CS8602: Dereference of a possibly null reference. // true => () => s1.ToString(), Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(11, 34), // (12,35): warning CS8603: Possible null reference return. // false => () => s1?.ToString() Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s1?.ToString()").WithLocation(12, 35) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void TargetTypedSwitch_07() { var comp = CreateCompilation(@" interface I {} class A : I {} class B : I {} class C { static void M(I i, A a, B? b, bool @bool) { M1(i, @bool switch { true => a, false => b }).ToString(); } static T M1<T>(T t1, T t2) => t1; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): warning CS8604: Possible null reference argument for parameter 't2' in 'I C.M1<I>(I t1, I t2)'. // M1(i, @bool switch { true => a, false => b }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "@bool switch { true => a, false => b }").WithArguments("t2", "I C.M1<I>(I t1, I t2)").WithLocation(9, 15) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void TargetTypedSwitch_08() { var comp = CreateCompilation(@" C? c = """".Length switch { > 0 => new A(), _ => new B() }; c.ToString(); class C { } class A { public static implicit operator C?(A a) => null; } class B { public static implicit operator C?(B b) => null; } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,1): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(3, 1) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void TargetTypedSwitch_09() { var comp = CreateCompilation(@" C? c = true switch { true => new A(), false => new B() }; c.ToString(); class C { } class A { public static implicit operator C(A a) => new C(); } class B { public static implicit operator C?(B b) => null; } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void TargetTypedSwitch_10() { var comp = CreateCompilation(@" C? c = false switch { true => new A(), false => new B() }; c.ToString(); class C { } class A { public static implicit operator C?(A a) => null; } class B { public static implicit operator C(B b) => new C(); } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/Core/Portable/ChangeSignature/ChangeSignatureTelemetryLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Internal.Log; namespace Microsoft.CodeAnalysis.ChangeSignature { internal class ChangeSignatureLogger { private const string Maximum = nameof(Maximum); private const string Minimum = nameof(Minimum); private const string Mean = nameof(Mean); private static readonly LogAggregator s_logAggregator = new(); private static readonly StatisticLogAggregator s_statisticLogAggregator = new(); private static readonly HistogramLogAggregator s_histogramLogAggregator = new(bucketSize: 1000, maxBucketValue: 30000); internal enum ActionInfo { // Calculate % of successful dialog launches ChangeSignatureDialogLaunched, ChangeSignatureDialogCommitted, ChangeSignatureCommitCompleted, // Calculate % of successful dialog launches AddParameterDialogLaunched, AddParameterDialogCommitted, // Which transformations were done CommittedSessionAddedRemovedReordered, CommittedSessionAddedRemovedOnly, CommittedSessionAddedReorderedOnly, CommittedSessionRemovedReorderedOnly, CommittedSessionAddedOnly, CommittedSessionRemovedOnly, CommittedSessionReorderedOnly, // Signature change specification details CommittedSession_OriginalParameterCount, CommittedSessionWithRemoved_NumberRemoved, CommittedSessionWithAdded_NumberAdded, // Signature change commit information CommittedSessionNumberOfDeclarationsUpdated, CommittedSessionNumberOfCallSitesUpdated, CommittedSessionCommitElapsedMS, // Added parameter binds or doesn't bind AddedParameterTypeBinds, // Added parameter required or optional w/default AddedParameterRequired, // Added parameter callsite value options AddedParameterValueExplicit, AddedParameterValueExplicitNamed, AddedParameterValueTODO, AddedParameterValueOmitted } internal static void LogChangeSignatureDialogLaunched() => s_logAggregator.IncreaseCount((int)ActionInfo.ChangeSignatureDialogLaunched); internal static void LogChangeSignatureDialogCommitted() => s_logAggregator.IncreaseCount((int)ActionInfo.ChangeSignatureDialogCommitted); internal static void LogAddParameterDialogLaunched() => s_logAggregator.IncreaseCount((int)ActionInfo.AddParameterDialogLaunched); internal static void LogAddParameterDialogCommitted() => s_logAggregator.IncreaseCount((int)ActionInfo.AddParameterDialogCommitted); internal static void LogTransformationInformation(int numOriginalParameters, int numParametersAdded, int numParametersRemoved, bool anyParametersReordered) { LogTransformationCombination(numParametersAdded > 0, numParametersRemoved > 0, anyParametersReordered); s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSession_OriginalParameterCount, numOriginalParameters); if (numParametersAdded > 0) { s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSessionWithAdded_NumberAdded, numParametersAdded); } if (numParametersRemoved > 0) { s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSessionWithRemoved_NumberRemoved, numParametersRemoved); } } private static void LogTransformationCombination(bool parametersAdded, bool parametersRemoved, bool parametersReordered) { // All three transformations if (parametersAdded && parametersRemoved && parametersReordered) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionAddedRemovedReordered); return; } // Two transformations if (parametersAdded && parametersRemoved) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionAddedRemovedOnly); return; } if (parametersAdded && parametersReordered) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionAddedReorderedOnly); return; } if (parametersRemoved && parametersReordered) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionRemovedReorderedOnly); return; } // One transformation if (parametersAdded) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionAddedOnly); return; } if (parametersRemoved) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionRemovedOnly); return; } if (parametersReordered) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionReorderedOnly); return; } } internal static void LogCommitInformation(int numDeclarationsUpdated, int numCallSitesUpdated, int elapsedMS) { s_logAggregator.IncreaseCount((int)ActionInfo.ChangeSignatureCommitCompleted); s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSessionNumberOfDeclarationsUpdated, numDeclarationsUpdated); s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSessionNumberOfCallSitesUpdated, numCallSitesUpdated); s_statisticLogAggregator.AddDataPoint((int)ActionInfo.CommittedSessionCommitElapsedMS, elapsedMS); s_histogramLogAggregator.IncreaseCount((int)ActionInfo.CommittedSessionCommitElapsedMS, elapsedMS); } internal static void LogAddedParameterTypeBinds() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterTypeBinds); } internal static void LogAddedParameterRequired() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterRequired); } internal static void LogAddedParameter_ValueExplicit() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterValueExplicit); } internal static void LogAddedParameter_ValueExplicitNamed() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterValueExplicitNamed); } internal static void LogAddedParameter_ValueTODO() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterValueTODO); } internal static void LogAddedParameter_ValueOmitted() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterValueOmitted); } internal static void ReportTelemetry() { Logger.Log(FunctionId.ChangeSignature_Data, KeyValueLogMessage.Create(m => { foreach (var kv in s_logAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); m[info] = kv.Value.GetCount(); } foreach (var kv in s_statisticLogAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); var statistics = kv.Value.GetStatisticResult(); m[CreateProperty(info, Maximum)] = statistics.Maximum; m[CreateProperty(info, Minimum)] = statistics.Minimum; m[CreateProperty(info, Mean)] = statistics.Mean; } foreach (var kv in s_histogramLogAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); m[$"{info}.BucketSize"] = kv.Value.BucketSize; m[$"{info}.MaxBucketValue"] = kv.Value.MaxBucketValue; m[$"{info}.Buckets"] = kv.Value.GetBucketsAsString(); } })); } private static string CreateProperty(string parent, string child) => parent + "." + child; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Internal.Log; namespace Microsoft.CodeAnalysis.ChangeSignature { internal class ChangeSignatureLogger { private const string Maximum = nameof(Maximum); private const string Minimum = nameof(Minimum); private const string Mean = nameof(Mean); private static readonly LogAggregator s_logAggregator = new(); private static readonly StatisticLogAggregator s_statisticLogAggregator = new(); private static readonly HistogramLogAggregator s_histogramLogAggregator = new(bucketSize: 1000, maxBucketValue: 30000); internal enum ActionInfo { // Calculate % of successful dialog launches ChangeSignatureDialogLaunched, ChangeSignatureDialogCommitted, ChangeSignatureCommitCompleted, // Calculate % of successful dialog launches AddParameterDialogLaunched, AddParameterDialogCommitted, // Which transformations were done CommittedSessionAddedRemovedReordered, CommittedSessionAddedRemovedOnly, CommittedSessionAddedReorderedOnly, CommittedSessionRemovedReorderedOnly, CommittedSessionAddedOnly, CommittedSessionRemovedOnly, CommittedSessionReorderedOnly, // Signature change specification details CommittedSession_OriginalParameterCount, CommittedSessionWithRemoved_NumberRemoved, CommittedSessionWithAdded_NumberAdded, // Signature change commit information CommittedSessionNumberOfDeclarationsUpdated, CommittedSessionNumberOfCallSitesUpdated, CommittedSessionCommitElapsedMS, // Added parameter binds or doesn't bind AddedParameterTypeBinds, // Added parameter required or optional w/default AddedParameterRequired, // Added parameter callsite value options AddedParameterValueExplicit, AddedParameterValueExplicitNamed, AddedParameterValueTODO, AddedParameterValueOmitted } internal static void LogChangeSignatureDialogLaunched() => s_logAggregator.IncreaseCount((int)ActionInfo.ChangeSignatureDialogLaunched); internal static void LogChangeSignatureDialogCommitted() => s_logAggregator.IncreaseCount((int)ActionInfo.ChangeSignatureDialogCommitted); internal static void LogAddParameterDialogLaunched() => s_logAggregator.IncreaseCount((int)ActionInfo.AddParameterDialogLaunched); internal static void LogAddParameterDialogCommitted() => s_logAggregator.IncreaseCount((int)ActionInfo.AddParameterDialogCommitted); internal static void LogTransformationInformation(int numOriginalParameters, int numParametersAdded, int numParametersRemoved, bool anyParametersReordered) { LogTransformationCombination(numParametersAdded > 0, numParametersRemoved > 0, anyParametersReordered); s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSession_OriginalParameterCount, numOriginalParameters); if (numParametersAdded > 0) { s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSessionWithAdded_NumberAdded, numParametersAdded); } if (numParametersRemoved > 0) { s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSessionWithRemoved_NumberRemoved, numParametersRemoved); } } private static void LogTransformationCombination(bool parametersAdded, bool parametersRemoved, bool parametersReordered) { // All three transformations if (parametersAdded && parametersRemoved && parametersReordered) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionAddedRemovedReordered); return; } // Two transformations if (parametersAdded && parametersRemoved) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionAddedRemovedOnly); return; } if (parametersAdded && parametersReordered) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionAddedReorderedOnly); return; } if (parametersRemoved && parametersReordered) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionRemovedReorderedOnly); return; } // One transformation if (parametersAdded) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionAddedOnly); return; } if (parametersRemoved) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionRemovedOnly); return; } if (parametersReordered) { s_logAggregator.IncreaseCount((int)ActionInfo.CommittedSessionReorderedOnly); return; } } internal static void LogCommitInformation(int numDeclarationsUpdated, int numCallSitesUpdated, int elapsedMS) { s_logAggregator.IncreaseCount((int)ActionInfo.ChangeSignatureCommitCompleted); s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSessionNumberOfDeclarationsUpdated, numDeclarationsUpdated); s_logAggregator.IncreaseCountBy((int)ActionInfo.CommittedSessionNumberOfCallSitesUpdated, numCallSitesUpdated); s_statisticLogAggregator.AddDataPoint((int)ActionInfo.CommittedSessionCommitElapsedMS, elapsedMS); s_histogramLogAggregator.IncreaseCount((int)ActionInfo.CommittedSessionCommitElapsedMS, elapsedMS); } internal static void LogAddedParameterTypeBinds() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterTypeBinds); } internal static void LogAddedParameterRequired() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterRequired); } internal static void LogAddedParameter_ValueExplicit() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterValueExplicit); } internal static void LogAddedParameter_ValueExplicitNamed() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterValueExplicitNamed); } internal static void LogAddedParameter_ValueTODO() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterValueTODO); } internal static void LogAddedParameter_ValueOmitted() { s_logAggregator.IncreaseCount((int)ActionInfo.AddedParameterValueOmitted); } internal static void ReportTelemetry() { Logger.Log(FunctionId.ChangeSignature_Data, KeyValueLogMessage.Create(m => { foreach (var kv in s_logAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); m[info] = kv.Value.GetCount(); } foreach (var kv in s_statisticLogAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); var statistics = kv.Value.GetStatisticResult(); m[CreateProperty(info, Maximum)] = statistics.Maximum; m[CreateProperty(info, Minimum)] = statistics.Minimum; m[CreateProperty(info, Mean)] = statistics.Mean; } foreach (var kv in s_histogramLogAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); m[$"{info}.BucketSize"] = kv.Value.BucketSize; m[$"{info}.MaxBucketValue"] = kv.Value.MaxBucketValue; m[$"{info}.Buckets"] = kv.Value.GetBucketsAsString(); } })); } private static string CreateProperty(string parent, string child) => parent + "." + child; } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Analyzers/CSharp/Tests/RemoveUnnecessaryDiscardDesignation/RemoveUnnecessaryDiscardDesignationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryDiscardDesignation; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryDiscardDesignation { using VerifyCS = CSharpCodeFixVerifier< CSharpRemoveUnnecessaryDiscardDesignationDiagnosticAnalyzer, CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider>; public class RemoveUnnecessaryDiscardDesignationTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestDeclarationPatternInSwitchStatement() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { switch (o) { case int [|_|]: break; } } }", FixedCode = @" class C { void M(object o) { switch (o) { case int: break; } } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestNotInCSharp8() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { switch (o) { case int _: break; } } }", LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestDeclarationPatternInSwitchExpression() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { int [|_|] => 0, }; } }", FixedCode = @" class C { void M(object o) { var v = o switch { int => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestDeclarationPatternInIfStatement() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o is int [|_|]) { } } }", FixedCode = @" class C { void M(object o) { if (o is int) { } } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestRecursivePropertyPattern() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { { } [|_|] => 0, }; } }", FixedCode = @" class C { void M(object o) { var v = o switch { { } => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestEmptyRecursiveParameterPattern() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { () [|_|] => 0, }; } }", FixedCode = @" class C { void M(object o) { var v = o switch { () => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestTwoElementRecursiveParameterPattern() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { (int i, int j) [|_|] => 0, }; } }", FixedCode = @" class C { void M(object o) { var v = o switch { (int i, int j) => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestNotWithOneElementRecursiveParameterPattern() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { (int i) _ => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestNestedFixAll() { await new VerifyCS.Test { TestCode = @" class C { void M(string o) { var v = o switch { { Length: int [|_|] } [|_|] => 1, }; } }", FixedCode = @" class C { void M(string o) { var v = o switch { { Length: int } => 1, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryDiscardDesignation; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryDiscardDesignation { using VerifyCS = CSharpCodeFixVerifier< CSharpRemoveUnnecessaryDiscardDesignationDiagnosticAnalyzer, CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider>; public class RemoveUnnecessaryDiscardDesignationTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestDeclarationPatternInSwitchStatement() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { switch (o) { case int [|_|]: break; } } }", FixedCode = @" class C { void M(object o) { switch (o) { case int: break; } } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestNotInCSharp8() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { switch (o) { case int _: break; } } }", LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestDeclarationPatternInSwitchExpression() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { int [|_|] => 0, }; } }", FixedCode = @" class C { void M(object o) { var v = o switch { int => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestDeclarationPatternInIfStatement() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { if (o is int [|_|]) { } } }", FixedCode = @" class C { void M(object o) { if (o is int) { } } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestRecursivePropertyPattern() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { { } [|_|] => 0, }; } }", FixedCode = @" class C { void M(object o) { var v = o switch { { } => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestEmptyRecursiveParameterPattern() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { () [|_|] => 0, }; } }", FixedCode = @" class C { void M(object o) { var v = o switch { () => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestTwoElementRecursiveParameterPattern() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { (int i, int j) [|_|] => 0, }; } }", FixedCode = @" class C { void M(object o) { var v = o switch { (int i, int j) => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestNotWithOneElementRecursiveParameterPattern() { await new VerifyCS.Test { TestCode = @" class C { void M(object o) { var v = o switch { (int i) _ => 0, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryDiscardDesignation)] public async Task TestNestedFixAll() { await new VerifyCS.Test { TestCode = @" class C { void M(string o) { var v = o switch { { Length: int [|_|] } [|_|] => 1, }; } }", FixedCode = @" class C { void M(string o) { var v = o switch { { Length: int } => 1, }; } }", LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/EditorFeatures/Core/Implementation/Workspaces/ProjectCacheServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces { [ExportWorkspaceServiceFactory(typeof(IProjectCacheHostService), ServiceLayer.Editor)] [Shared] internal partial class ProjectCacheHostServiceFactory : IWorkspaceServiceFactory { private static readonly TimeSpan s_implicitCacheTimeout = TimeSpan.FromMilliseconds(10000); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ProjectCacheHostServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (workspaceServices.Workspace.Kind != WorkspaceKind.Host) { return new ProjectCacheService(workspaceServices.Workspace); } var service = new ProjectCacheService(workspaceServices.Workspace, s_implicitCacheTimeout); // Also clear the cache when the solution is cleared or removed. workspaceServices.Workspace.WorkspaceChanged += (s, e) => { if (e.Kind == WorkspaceChangeKind.SolutionCleared || e.Kind == WorkspaceChangeKind.SolutionRemoved) { service.ClearImplicitCache(); } }; return service; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces { [ExportWorkspaceServiceFactory(typeof(IProjectCacheHostService), ServiceLayer.Editor)] [Shared] internal partial class ProjectCacheHostServiceFactory : IWorkspaceServiceFactory { private static readonly TimeSpan s_implicitCacheTimeout = TimeSpan.FromMilliseconds(10000); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ProjectCacheHostServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (workspaceServices.Workspace.Kind != WorkspaceKind.Host) { return new ProjectCacheService(workspaceServices.Workspace); } var service = new ProjectCacheService(workspaceServices.Workspace, s_implicitCacheTimeout); // Also clear the cache when the solution is cleared or removed. workspaceServices.Workspace.WorkspaceChanged += (s, e) => { if (e.Kind == WorkspaceChangeKind.SolutionCleared || e.Kind == WorkspaceChangeKind.SolutionRemoved) { service.ClearImplicitCache(); } }; return service; } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/CSharp/Portable/CodeRefactorings/NodeSelectionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings { internal static class NodeSelectionHelpers { internal static async Task<SyntaxNode> GetSelectedDeclarationOrVariableAsync(CodeRefactoringContext context) { // Consider: // MemberDeclaration: member that can be declared in type (those are the ones we can pull up) // VariableDeclaratorSyntax: for fields the MemberDeclaration can actually represent multiple declarations, e.g. `int a = 0, b = 1;`. // ..Since the user might want to select & pull up only one of them (e.g. `int a = 0, [|b = 1|];` we also look for closest VariableDeclaratorSyntax. return await context.TryGetRelevantNodeAsync<MemberDeclarationSyntax>().ConfigureAwait(false) as SyntaxNode ?? await context.TryGetRelevantNodeAsync<VariableDeclaratorSyntax>().ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings { internal static class NodeSelectionHelpers { internal static async Task<SyntaxNode> GetSelectedDeclarationOrVariableAsync(CodeRefactoringContext context) { // Consider: // MemberDeclaration: member that can be declared in type (those are the ones we can pull up) // VariableDeclaratorSyntax: for fields the MemberDeclaration can actually represent multiple declarations, e.g. `int a = 0, b = 1;`. // ..Since the user might want to select & pull up only one of them (e.g. `int a = 0, [|b = 1|];` we also look for closest VariableDeclaratorSyntax. return await context.TryGetRelevantNodeAsync<MemberDeclarationSyntax>().ConfigureAwait(false) as SyntaxNode ?? await context.TryGetRelevantNodeAsync<VariableDeclaratorSyntax>().ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./docs/compilers/CSharp/Compiler Breaking Changes - DotNet 6.md
## This document lists known breaking changes in Roslyn in C# 10.0 which will be introduced with .NET 6. 1. Beginning with C# 10.0, null suppression operator is no longer allowed in patterns. ```csharp void M(object o) { if (o is null!) {} // error } ```
## This document lists known breaking changes in Roslyn in C# 10.0 which will be introduced with .NET 6. 1. Beginning with C# 10.0, null suppression operator is no longer allowed in patterns. ```csharp void M(object o) { if (o is null!) {} // error } ``` 2. In C# 10, lambda expressions and method groups with inferred type are implicitly convertible to `System.MulticastDelegate`, and bases classes and interfaces of `System.MulticastDelegate` including `object`, and lambda expressions and method groups are implicitly convertible to `System.Linq.Expressions.Expression` and `System.Linq.Expressions.LambdaExpression`. These are _function_type_conversions_. The new implicit conversions may change overload resolution in cases where the compiler searches iteratively for overloads and stops at the first type or namespace scope containing any applicable overloads. a. Instance and extension methods ```csharp class C { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(); C#10: C.M() c.M(() => { }); // C#9: E.M(); C#10: C.M() } void M(System.Delegate d) { } } static class E { public static void M(this object x, System.Action y) { } } ``` b. Base and derived methods ```csharp using System; using System.Linq.Expressions; class A { public void M(Func<int> f) { } public object this[Func<int> f] => null; public static A operator+(A a, Func<int> f) => a; } class B : A { public void M(Expression e) { } public object this[Delegate d] => null; public static B operator+(B b, Delegate d) => b; } class Program { static int F() => 1; static void Main() { var b = new B(); b.M(() => 1); // C#9: A.M(); C#10: B.M() _ = b[() => 2]; // C#9: A.this[]; C#10: B.this[] _ = b + F; // C#9: A.operator+(); C#10: B.operator+() } } ``` c. Method group conversion to `Expression` or `LambdaExpression` ```csharp using System; using System.Linq.Expressions; var c = new C(); c.M(F); // error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression' static int F() => 0; class C { public void M(Expression e) { } } static class E { public static void M(this object o, Func<int> a) { } } ``` 3. In C#10, a lambda expression with inferred type may contribute an argument type that affects overload resolution. ```csharp using System; class Program { static void F(Func<Func<object>> f, int i) { } static void F(Func<Func<int>> f, object o) { } static void Main() { F(() => () => 1, 2); // C#9: F(Func<Func<object>>, int); C#10: ambiguous } } ```
1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./docs/compilers/CSharp/Compiler Breaking Changes - post DotNet 5.md
## This document lists known breaking changes in Roslyn after .NET 5. 1. https://github.com/dotnet/roslyn/issues/46044 In C# 9.0 (Visual Studio 16.9), a warning is reported when assigning `default` to, or when casting a possibly `null` value to a type parameter type that is not constrained to value types or reference types. To avoid the warning, the type can be annotated with `?`. ```C# static void F1<T>(object? obj) { T t1 = default; // warning CS8600: Converting possible null value to non-nullable type t1 = (T)obj; // warning CS8600: Converting possible null value to non-nullable type T? t2 = default; // ok t2 = (T?)obj; // ok } ``` 2. https://github.com/dotnet/roslyn/pull/50755 In .NET 5.0.200 (Visual Studio 16.9), if there is a common type between the two branches of a conditional expression, that type is the type of the conditional expression. This is a breaking change from 5.0.103 (Visual Studio 16.8) which due to a bug incorrectly used the target type of the conditional expression as the type even if there was a common type between the two branches. This latest change aligns the compiler behavior with the C# specification and with versions of the compiler before .NET 5.0. ```C# static short F1(bool b) { // 16.7, 16.9 : CS0266: Cannot implicitly convert type 'int' to 'short' // 16.8 : ok // 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0 return b ? 1 : 2; } static object F2(bool b, short? a) { // 16.7, 16.9 : int // 16.8 : short // 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0 return a ?? (b ? 1 : 2); } ``` 3. https://github.com/dotnet/roslyn/issues/52630 In C# 9 (.NET 5, Visual Studio 16.9), it is possible that a record uses a hidden member from a base type as a positional member. In Visual Studio 16.10, this is now an error: ```csharp record Base { public int I { get; init; } } record Derived(int I) // The positional member 'Base.I' found corresponding to this parameter is hidden. : Base { public int I() { return 0; } } ``` 4. In C# 10, lambda expressions and method groups are implicitly convertible to `System.MulticastDelegate`, or any base classes or interfaces of `System.MulticastDelegate` including `object`, and lambda expressions are implicitly convertible to `System.Linq.Expressions.Expression`. This is a breaking change to overload resolution if there exists an applicable overload with a parameter of type `System.MulticastDelegate`, or a parameter of a type in the base types or interfaces of `System.MulticastDelegate`, or a parameter of type `System.Linq.Expressions.Expression`, and the closest applicable extension method overload with a strongly-typed delegate parameter is in an enclosing namespace. ```C# class C { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(), C#10: C.M() c.M(() => { }); // C#9: E.M(), C#10: C.M() } void M(System.Delegate d) { } } static class E { public static void M(this object x, System.Action y) { } } ``` 5. In .NET 5 and Visual Studio 16.9 (and earlier), top-level statements could be used in a program containing a type named `Program`. In .NET 6 and Visual Studio 17.0, top-level statements generate a partial declaration of a `Program` class, so any user-defined `Program` type must also be a partial class. ```csharp System.Console.Write("top-level"); Method(); partial class Program { static void Method() { } } ``` 6. https://github.com/dotnet/roslyn/issues/53021 C# will now report an error for a misplaced ```::``` token in explicit interface implementation. In this example code: ``` C# void N::I::M() { } ``` Previous versions of Roslyn wouldn't report any errors. We now report an error for a ```::``` token before M.
## This document lists known breaking changes in Roslyn after .NET 5. 1. https://github.com/dotnet/roslyn/issues/46044 In C# 9.0 (Visual Studio 16.9), a warning is reported when assigning `default` to, or when casting a possibly `null` value to a type parameter type that is not constrained to value types or reference types. To avoid the warning, the type can be annotated with `?`. ```C# static void F1<T>(object? obj) { T t1 = default; // warning CS8600: Converting possible null value to non-nullable type t1 = (T)obj; // warning CS8600: Converting possible null value to non-nullable type T? t2 = default; // ok t2 = (T?)obj; // ok } ``` 2. https://github.com/dotnet/roslyn/pull/50755 In .NET 5.0.200 (Visual Studio 16.9), if there is a common type between the two branches of a conditional expression, that type is the type of the conditional expression. This is a breaking change from 5.0.103 (Visual Studio 16.8) which due to a bug incorrectly used the target type of the conditional expression as the type even if there was a common type between the two branches. This latest change aligns the compiler behavior with the C# specification and with versions of the compiler before .NET 5.0. ```C# static short F1(bool b) { // 16.7, 16.9 : CS0266: Cannot implicitly convert type 'int' to 'short' // 16.8 : ok // 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0 return b ? 1 : 2; } static object F2(bool b, short? a) { // 16.7, 16.9 : int // 16.8 : short // 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0 return a ?? (b ? 1 : 2); } ``` 3. https://github.com/dotnet/roslyn/issues/52630 In C# 9 (.NET 5, Visual Studio 16.9), it is possible that a record uses a hidden member from a base type as a positional member. In Visual Studio 16.10, this is now an error: ```csharp record Base { public int I { get; init; } } record Derived(int I) // The positional member 'Base.I' found corresponding to this parameter is hidden. : Base { public int I() { return 0; } } ``` 4. In .NET 5 and Visual Studio 16.9 (and earlier), top-level statements could be used in a program containing a type named `Program`. In .NET 6 and Visual Studio 17.0, top-level statements generate a partial declaration of a `Program` class, so any user-defined `Program` type must also be a partial class. ```csharp System.Console.Write("top-level"); Method(); partial class Program { static void Method() { } } ``` 5. https://github.com/dotnet/roslyn/issues/53021 C# will now report an error for a misplaced ```::``` token in explicit interface implementation. In this example code: ``` C# void N::I::M() { } ``` Previous versions of Roslyn wouldn't report any errors. We now report an error for a ```::``` token before M.
1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MemberResolutionResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Represents the results of overload resolution for a single member. /// </summary> [SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")] internal struct MemberResolutionResult<TMember> where TMember : Symbol { private readonly TMember _member; private readonly TMember _leastOverriddenMember; private readonly MemberAnalysisResult _result; internal MemberResolutionResult(TMember member, TMember leastOverriddenMember, MemberAnalysisResult result) { _member = member; _leastOverriddenMember = leastOverriddenMember; _result = result; } internal bool IsNull { get { return (object)_member == null; } } internal bool IsNotNull { get { return (object)_member != null; } } /// <summary> /// The member considered during overload resolution. /// </summary> public TMember Member { get { return _member; } } /// <summary> /// The least overridden member that is accessible from the call site that performed overload resolution. /// Typically a virtual or abstract method (but not necessarily). /// </summary> /// <remarks> /// The member whose parameter types and params modifiers were considered during overload resolution. /// </remarks> internal TMember LeastOverriddenMember { get { return _leastOverriddenMember; } } /// <summary> /// Indicates why the compiler accepted or rejected the member during overload resolution. /// </summary> public MemberResolutionKind Resolution { get { return Result.Kind; } } /// <summary> /// Returns true if the compiler accepted this member as the sole correct result of overload resolution. /// </summary> public bool IsValid { get { return Result.IsValid; } } public bool IsApplicable { get { return Result.IsApplicable; } } internal MemberResolutionResult<TMember> Worse() { return new MemberResolutionResult<TMember>(Member, LeastOverriddenMember, MemberAnalysisResult.Worse()); } internal MemberResolutionResult<TMember> Worst() { return new MemberResolutionResult<TMember>(Member, LeastOverriddenMember, MemberAnalysisResult.Worst()); } internal bool HasUseSiteDiagnosticToReport { get { return _result.HasUseSiteDiagnosticToReportFor(_member); } } /// <summary> /// The result of member analysis. /// </summary> internal MemberAnalysisResult Result { get { return _result; } } public override bool Equals(object obj) { throw new NotSupportedException(); } public override int GetHashCode() { throw new NotSupportedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Represents the results of overload resolution for a single member. /// </summary> [SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")] internal readonly struct MemberResolutionResult<TMember> where TMember : Symbol { private readonly TMember _member; private readonly TMember _leastOverriddenMember; private readonly MemberAnalysisResult _result; /// <summary> /// At least one type argument was inferred from a function type. /// </summary> internal readonly bool HasTypeArgumentInferredFromFunctionType; internal MemberResolutionResult(TMember member, TMember leastOverriddenMember, MemberAnalysisResult result, bool hasTypeArgumentInferredFromFunctionType = false) { _member = member; _leastOverriddenMember = leastOverriddenMember; _result = result; HasTypeArgumentInferredFromFunctionType = hasTypeArgumentInferredFromFunctionType; } internal bool IsNull { get { return (object)_member == null; } } internal bool IsNotNull { get { return (object)_member != null; } } /// <summary> /// The member considered during overload resolution. /// </summary> public TMember Member { get { return _member; } } /// <summary> /// The least overridden member that is accessible from the call site that performed overload resolution. /// Typically a virtual or abstract method (but not necessarily). /// </summary> /// <remarks> /// The member whose parameter types and params modifiers were considered during overload resolution. /// </remarks> internal TMember LeastOverriddenMember { get { return _leastOverriddenMember; } } /// <summary> /// Indicates why the compiler accepted or rejected the member during overload resolution. /// </summary> public MemberResolutionKind Resolution { get { return Result.Kind; } } /// <summary> /// Returns true if the compiler accepted this member as the sole correct result of overload resolution. /// </summary> public bool IsValid { get { return Result.IsValid; } } public bool IsApplicable { get { return Result.IsApplicable; } } internal MemberResolutionResult<TMember> Worse() { return new MemberResolutionResult<TMember>(Member, LeastOverriddenMember, MemberAnalysisResult.Worse()); } internal MemberResolutionResult<TMember> Worst() { return new MemberResolutionResult<TMember>(Member, LeastOverriddenMember, MemberAnalysisResult.Worst()); } internal bool HasUseSiteDiagnosticToReport { get { return _result.HasUseSiteDiagnosticToReportFor(_member); } } /// <summary> /// The result of member analysis. /// </summary> internal MemberAnalysisResult Result { get { return _result; } } public override bool Equals(object? obj) { throw new NotSupportedException(); } public override int GetHashCode() { throw new NotSupportedException(); } } }
1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly CSharpCompilation _compilation; private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly TypeWithAnnotations[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/nullable-reference-types-specification.md#fixing // If the resulting candidate is a reference type and *all* of the exact bounds or *any* of // the lower bounds are nullable reference types, `null` or `default`, then `?` is added to // the resulting candidate, making it a nullable reference type. // // This set of bounds effectively tracks whether a typeless null expression (i.e. null // literal) was used as an argument to a parameter whose type is one of this method's type // parameters. Because such expressions only occur as by-value inputs, we only need to track // the lower bounds, not the exact or upper bounds. private readonly NullableAnnotation[] _nullableAnnotationLowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(false, default(ImmutableArray<TypeWithAnnotations>)); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _compilation = compilation; _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new TypeWithAnnotations[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _nullableAnnotationLowerBounds = new NullableAnnotation[methodTypeParameters.Length]; Debug.Assert(_nullableAnnotationLowerBounds.All(annotation => annotation.IsNotAnnotated())); _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i]; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults() { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { if (_fixedResults[i].HasType) { if (!_fixedResults[i].Type.IsErrorType()) { if (_conversions.IncludeNullability && _nullableAnnotationLowerBounds[i].IsAnnotated()) { _fixedResults[i] = _fixedResults[i].AsAnnotated(); } continue; } var errorTypeName = _fixedResults[i].Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)); } return _fixedResults.AsImmutable(); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(_methodTypeParameters.Length); for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { fixedArguments.Add(IsUnfixed(iParam) ? TypeWithAnnotations.Create(_methodTypeParameters[iParam]) : _fixedResults[iParam]); } TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments.ToImmutableAndFree()); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); return new MethodTypeInferenceResult(success, GetResults()); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, an explicit type parameter // SPEC: inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda && target.Type.GetDelegateType() is { }) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.GetTypeOrFunctionType())) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } else if (IsUnfixedTypeParameter(target) && kind is ExactOrBoundsKind.LowerBound) { var ordinal = ((TypeParameterSymbol)target.Type).Ordinal; var typeWithAnnotations = _extensions.GetTypeWithAnnotations(argument); _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(typeWithAnnotations.NullableAnnotation); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var typeParameter = _methodTypeParameters[iParam]; var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); if (!best.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(_compilation, _conversions.WithNullability(false), typeParameter, exact, lower, upper, ref discardedUseSiteInfo); // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static TypeWithAnnotations Fix( CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet<TypeWithAnnotations>? exact, HashSet<TypeWithAnnotations>? lower, HashSet<TypeWithAnnotations>? upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); Debug.Assert(!containsFunctionTypes(exact)); Debug.Assert(!containsFunctionTypes(upper)); // Function types are dropped if there are any non-function types. if (containsFunctionTypes(lower) && (containsNonFunctionTypes(lower) || containsNonFunctionTypes(exact) || containsNonFunctionTypes(upper))) { lower = removeFunctionTypes(lower); } // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Upper bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); if (isFunctionType(best, out var functionType)) { // Realize the type as TDelegate, or Expression<TDelegate> if the type parameter // is constrained to System.Linq.Expressions.Expression. var resultType = functionType.GetInternalDelegateType(); if (hasExpressionTypeConstraint(typeParameter)) { var expressionOfTType = compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T); resultType = expressionOfTType.Construct(resultType); } best = TypeWithAnnotations.Create(resultType, best.NullableAnnotation); } return best; static bool containsFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => isFunctionType(t, out _)) == true; } static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => !isFunctionType(t, out _)) == true; } static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? functionType) { functionType = type.Type as FunctionTypeSymbol; return functionType is not null; } static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameter) { var constraintTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics; return constraintTypes.Any(t => isExpressionType(t.Type)); } static bool isExpressionType(TypeSymbol? type) { while (type is { }) { if (type.IsGenericOrNonGenericExpressionType(out _)) { return true; } type = type.BaseTypeNoUseSiteDiagnostics; } return false; } static HashSet<TypeWithAnnotations>? removeFunctionTypes(HashSet<TypeWithAnnotations> types) { HashSet<TypeWithAnnotations>? updated = null; foreach (var type in types) { if (!isFunctionType(type, out _)) { updated ??= new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); updated.Add(type); } } return updated; } } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( compilation, conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } #nullable enable /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments() { return _fixedResults.AsImmutable(); } private static bool IsReallyAType(TypeSymbol? type) { return type is { } && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal readonly struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; /// <summary> /// At least one type argument was inferred from a function type. /// </summary> public readonly bool HasTypeArgumentInferredFromFunctionType; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments, bool hasTypeArgumentInferredFromFunctionType) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; this.HasTypeArgumentInferredFromFunctionType = hasTypeArgumentInferredFromFunctionType; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly CSharpCompilation _compilation; private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly (TypeWithAnnotations Type, bool FromFunctionType)[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/nullable-reference-types-specification.md#fixing // If the resulting candidate is a reference type and *all* of the exact bounds or *any* of // the lower bounds are nullable reference types, `null` or `default`, then `?` is added to // the resulting candidate, making it a nullable reference type. // // This set of bounds effectively tracks whether a typeless null expression (i.e. null // literal) was used as an argument to a parameter whose type is one of this method's type // parameters. Because such expressions only occur as by-value inputs, we only need to track // the lower bounds, not the exact or upper bounds. private readonly NullableAnnotation[] _nullableAnnotationLowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(success: false, inferredTypeArguments: default, hasTypeArgumentInferredFromFunctionType: false); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _compilation = compilation; _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new (TypeWithAnnotations, bool)[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _nullableAnnotationLowerBounds = new NullableAnnotation[methodTypeParameters.Length]; Debug.Assert(_nullableAnnotationLowerBounds.All(annotation => annotation.IsNotAnnotated())); _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i].Type; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults(out bool inferredFromFunctionType) { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { var fixedResultType = _fixedResults[i].Type; if (fixedResultType.HasType) { if (!fixedResultType.Type.IsErrorType()) { if (_conversions.IncludeNullability && _nullableAnnotationLowerBounds[i].IsAnnotated()) { _fixedResults[i] = _fixedResults[i] with { Type = fixedResultType.AsAnnotated() }; } continue; } var errorTypeName = fixedResultType.Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = (TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)), false); } return GetInferredTypeArguments(out inferredFromFunctionType); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].Type.HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = _methodTypeParameters.SelectAsArray( static (typeParameter, i, self) => self.IsUnfixed(i) ? TypeWithAnnotations.Create(typeParameter) : self._fixedResults[i].Type, this); TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); var inferredTypeArguments = GetResults(out bool inferredFromFunctionType); return new MethodTypeInferenceResult(success, inferredTypeArguments, inferredFromFunctionType); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, an explicit type parameter // SPEC: inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda && target.Type.GetDelegateType() is { }) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.GetTypeOrFunctionType())) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } else if (IsUnfixedTypeParameter(target) && kind is ExactOrBoundsKind.LowerBound) { var ordinal = ((TypeParameterSymbol)target.Type).Ordinal; var typeWithAnnotations = _extensions.GetTypeWithAnnotations(argument); _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(typeWithAnnotations.NullableAnnotation); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var typeParameter = _methodTypeParameters[iParam]; var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); if (!best.Type.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(_compilation, _conversions.WithNullability(false), typeParameter, exact, lower, upper, ref discardedUseSiteInfo).Type; // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static (TypeWithAnnotations Type, bool FromFunctionType) Fix( CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet<TypeWithAnnotations>? exact, HashSet<TypeWithAnnotations>? lower, HashSet<TypeWithAnnotations>? upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); Debug.Assert(!containsFunctionTypes(exact)); Debug.Assert(!containsFunctionTypes(upper)); // Function types are dropped if there are any non-function types. if (containsFunctionTypes(lower) && (containsNonFunctionTypes(lower) || containsNonFunctionTypes(exact) || containsNonFunctionTypes(upper))) { lower = removeFunctionTypes(lower); } // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Upper bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); bool fromFunctionType = false; if (isFunctionType(best, out var functionType)) { // Realize the type as TDelegate, or Expression<TDelegate> if the type parameter // is constrained to System.Linq.Expressions.Expression. var resultType = functionType.GetInternalDelegateType(); if (hasExpressionTypeConstraint(typeParameter)) { var expressionOfTType = compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T); resultType = expressionOfTType.Construct(resultType); } best = TypeWithAnnotations.Create(resultType, best.NullableAnnotation); fromFunctionType = true; } return (best, fromFunctionType); static bool containsFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => isFunctionType(t, out _)) == true; } static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => !isFunctionType(t, out _)) == true; } static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? functionType) { functionType = type.Type as FunctionTypeSymbol; return functionType is not null; } static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameter) { var constraintTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics; return constraintTypes.Any(t => isExpressionType(t.Type)); } static bool isExpressionType(TypeSymbol? type) { while (type is { }) { if (type.IsGenericOrNonGenericExpressionType(out _)) { return true; } type = type.BaseTypeNoUseSiteDiagnostics; } return false; } static HashSet<TypeWithAnnotations>? removeFunctionTypes(HashSet<TypeWithAnnotations> types) { HashSet<TypeWithAnnotations>? updated = null; foreach (var type in types) { if (!isFunctionType(type, out _)) { updated ??= new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); updated.Add(type); } } return updated; } } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( compilation, conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(out _); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } #nullable enable /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments(out bool inferredFromFunctionType) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_fixedResults.Length); inferredFromFunctionType = false; foreach (var fixedResult in _fixedResults) { builder.Add(fixedResult.Type); if (fixedResult.FromFunctionType) { inferredFromFunctionType = true; } } return builder.ToImmutableAndFree(); } private static bool IsReallyAType(TypeSymbol? type) { return type is { } && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolution.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal enum BetterResult { Left, Right, Neither, Equal } internal sealed partial class OverloadResolution { private readonly Binder _binder; public OverloadResolution(Binder binder) { _binder = binder; } private CSharpCompilation Compilation { get { return _binder.Compilation; } } private Conversions Conversions { get { return _binder.Conversions; } } // lazily compute if the compiler is in "strict" mode (rather than duplicating bugs for compatibility) private bool? _strict; private bool Strict { get { if (_strict.HasValue) return _strict.Value; bool value = _binder.Compilation.FeatureStrictEnabled; _strict = value; return value; } } // UNDONE: This List<MethodResolutionResult> deal should probably be its own data structure. // We need an indexable collection of mappings from method candidates to their up-to-date // overload resolution status. It must be fast and memory efficient, but it will very often // contain just 1 candidate. private static bool AnyValidResult<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results) where TMember : Symbol { foreach (var result in results) { if (result.IsValid) { return true; } } return false; } private static bool SingleValidResult<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results) where TMember : Symbol { bool oneValid = false; foreach (var result in results) { if (result.IsValid) { if (oneValid) { return false; } oneValid = true; } } return oneValid; } // Perform overload resolution on the given method group, with the given arguments and // names. The names can be null if no names were supplied to any arguments. public void ObjectCreationOverloadResolution(ImmutableArray<MethodSymbol> constructors, AnalyzedArguments arguments, OverloadResolutionResult<MethodSymbol> result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var results = result.ResultsBuilder; // First, attempt overload resolution not getting complete results. PerformObjectCreationOverloadResolution(results, constructors, arguments, false, ref useSiteInfo); if (!OverloadResolutionResultIsValid(results, arguments.HasDynamicArgument)) { // We didn't get a single good result. Get full results of overload resolution and return those. result.Clear(); PerformObjectCreationOverloadResolution(results, constructors, arguments, true, ref useSiteInfo); } } // Perform overload resolution on the given method group, with the given arguments and // names. The names can be null if no names were supplied to any arguments. public void MethodInvocationOverloadResolution( ArrayBuilder<MethodSymbol> methods, ArrayBuilder<TypeWithAnnotations> typeArguments, BoundExpression receiver, AnalyzedArguments arguments, OverloadResolutionResult<MethodSymbol> result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool isMethodGroupConversion = false, bool allowRefOmittedArguments = false, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { MethodOrPropertyOverloadResolution( methods, typeArguments, receiver, arguments, result, isMethodGroupConversion, allowRefOmittedArguments, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, in callingConventionInfo); } // Perform overload resolution on the given property group, with the given arguments and // names. The names can be null if no names were supplied to any arguments. public void PropertyOverloadResolution( ArrayBuilder<PropertySymbol> indexers, BoundExpression receiverOpt, AnalyzedArguments arguments, OverloadResolutionResult<PropertySymbol> result, bool allowRefOmittedArguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<TypeWithAnnotations> typeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); MethodOrPropertyOverloadResolution( indexers, typeArguments, receiverOpt, arguments, result, isMethodGroupConversion: false, allowRefOmittedArguments: allowRefOmittedArguments, useSiteInfo: ref useSiteInfo, callingConventionInfo: default); typeArguments.Free(); } internal void MethodOrPropertyOverloadResolution<TMember>( ArrayBuilder<TMember> members, ArrayBuilder<TypeWithAnnotations> typeArguments, BoundExpression receiver, AnalyzedArguments arguments, OverloadResolutionResult<TMember> result, bool isMethodGroupConversion, bool allowRefOmittedArguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) where TMember : Symbol { var results = result.ResultsBuilder; // First, attempt overload resolution not getting complete results. PerformMemberOverloadResolution( results, members, typeArguments, receiver, arguments, completeResults: false, isMethodGroupConversion, returnRefKind, returnType, allowRefOmittedArguments, isFunctionPointerResolution, callingConventionInfo, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm); if (!OverloadResolutionResultIsValid(results, arguments.HasDynamicArgument)) { // We didn't get a single good result. Get full results of overload resolution and return those. result.Clear(); PerformMemberOverloadResolution( results, members, typeArguments, receiver, arguments, completeResults: true, isMethodGroupConversion, returnRefKind, returnType, allowRefOmittedArguments, isFunctionPointerResolution, callingConventionInfo, ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); } } private static bool OverloadResolutionResultIsValid<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, bool hasDynamicArgument) where TMember : Symbol { // If there were no dynamic arguments then overload resolution succeeds if there is exactly one method // that is applicable and not worse than another method. // // If there were dynamic arguments then overload resolution succeeds if there were one or more applicable // methods; which applicable method that will be invoked, if any, will be worked out at runtime. // // Note that we could in theory do a better job of detecting situations that we know will fail. We do not // treat methods that violate generic type constraints as inapplicable; rather, if such a method is chosen // as the best method we give an error during the "final validation" phase. In the dynamic argument // scenario there could be two methods, both applicable, ambiguous as to which is better, and neither // would pass final validation. In that case we could give the error at compile time, but we do not. if (hasDynamicArgument) { foreach (var curResult in results) { if (curResult.Result.IsApplicable) { return true; } } return false; } return SingleValidResult(results); } // Perform method/indexer overload resolution, storing the results into "results". If // completeResults is false, then invalid results don't have to be stored. The results will // still contain all possible successful resolution. private void PerformMemberOverloadResolution<TMember>( ArrayBuilder<MemberResolutionResult<TMember>> results, ArrayBuilder<TMember> members, ArrayBuilder<TypeWithAnnotations> typeArguments, BoundExpression receiver, AnalyzedArguments arguments, bool completeResults, bool isMethodGroupConversion, RefKind returnRefKind, TypeSymbol returnType, bool allowRefOmittedArguments, bool isFunctionPointerResolution, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true) where TMember : Symbol { // SPEC: The binding-time processing of a method invocation of the form M(A), where M is a // SPEC: method group (possibly including a type-argument-list), and A is an optional // SPEC: argument-list, consists of the following steps: // NOTE: We use a quadratic algorithm to determine which members override/hide // each other (i.e. we compare them pairwise). We could move to a linear // algorithm that builds the closure set of overridden/hidden members and then // uses that set to filter the candidate, but that would still involve realizing // a lot of PE symbols. Instead, we partition the candidates by containing type. // With this information, we can efficiently skip checks where the (potentially) // overriding or hiding member is not in a subtype of the type containing the // (potentially) overridden or hidden member. Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt = null; if (members.Count > 50) // TODO: fine-tune this value { containingTypeMapOpt = PartitionMembersByContainingType(members); } // SPEC: The set of candidate methods for the method invocation is constructed. for (int i = 0; i < members.Count; i++) { AddMemberToCandidateSet( members[i], results, members, typeArguments, receiver, arguments, completeResults, isMethodGroupConversion, allowRefOmittedArguments, containingTypeMapOpt, inferWithDynamic: inferWithDynamic, useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); } // CONSIDER: use containingTypeMapOpt for RemoveLessDerivedMembers? ClearContainingTypeMap(ref containingTypeMapOpt); // Remove methods that are inaccessible because their inferred type arguments are inaccessible. // It is not clear from the spec how or where this is supposed to occur. RemoveInaccessibleTypeArguments(results, ref useSiteInfo); // SPEC: The set of candidate methods is reduced to contain only methods from the most derived types. RemoveLessDerivedMembers(results, ref useSiteInfo); if (Compilation.LanguageVersion.AllowImprovedOverloadCandidates()) { RemoveStaticInstanceMismatches(results, arguments, receiver); RemoveConstraintViolations(results, template: new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo)); if (isMethodGroupConversion) { RemoveDelegateConversionsWithWrongReturnType(results, ref useSiteInfo, returnRefKind, returnType, isFunctionPointerResolution); } } if (isFunctionPointerResolution) { RemoveCallingConventionMismatches(results, callingConventionInfo); RemoveMethodsNotDeclaredStatic(results); } // NB: As in dev12, we do this AFTER removing less derived members. // Also note that less derived members are not actually removed - they are simply flagged. ReportUseSiteInfo(results, ref useSiteInfo); // SPEC: If the resulting set of candidate methods is empty, then further processing along the following steps are abandoned, // SPEC: and instead an attempt is made to process the invocation as an extension method invocation. If this fails, then no // SPEC: applicable methods exist, and a binding-time error occurs. if (!AnyValidResult(results)) { return; } // SPEC: The best method of the set of candidate methods is identified. If a single best method cannot be identified, // SPEC: the method invocation is ambiguous, and a binding-time error occurs. RemoveWorseMembers(results, arguments, ref useSiteInfo); // Note, the caller is responsible for "final validation", // as that is not part of overload resolution. } internal void FunctionPointerOverloadResolution( ArrayBuilder<FunctionPointerMethodSymbol> funcPtrBuilder, AnalyzedArguments analyzedArguments, OverloadResolutionResult<FunctionPointerMethodSymbol> overloadResolutionResult, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(funcPtrBuilder.Count == 1); Debug.Assert(funcPtrBuilder[0].Arity == 0); var typeArgumentsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); AddMemberToCandidateSet( funcPtrBuilder[0], overloadResolutionResult.ResultsBuilder, funcPtrBuilder, typeArgumentsBuilder, receiverOpt: null, analyzedArguments, completeResults: true, isMethodGroupConversion: false, allowRefOmittedArguments: false, containingTypeMapOpt: null, inferWithDynamic: false, ref useSiteInfo, allowUnexpandedForm: true); ReportUseSiteInfo(overloadResolutionResult.ResultsBuilder, ref useSiteInfo); } private void RemoveStaticInstanceMismatches<TMember>( ArrayBuilder<MemberResolutionResult<TMember>> results, AnalyzedArguments arguments, BoundExpression receiverOpt) where TMember : Symbol { // When the feature 'ImprovedOverloadCandidates' is enabled, we do not include instance members when the receiver // is a type, or static members when the receiver is an instance. This does not apply to extension method invocations, // because extension methods are only considered when the receiver is an instance. It also does not apply when the // receiver is a TypeOrValueExpression, which is used to handle the receiver of a Color-Color ambiguity, where either // an instance or a static member would be acceptable. if (arguments.IsExtensionMethodInvocation || Binder.IsTypeOrValueExpression(receiverOpt)) { return; } bool isImplicitReceiver = Binder.WasImplicitReceiver(receiverOpt); // isStaticContext includes both places where `this` isn't available, and places where it // cannot be used (e.g. a field initializer or a constructor-initializer) bool isStaticContext = !_binder.HasThis(!isImplicitReceiver, out bool inStaticContext) || inStaticContext; if (isImplicitReceiver && !isStaticContext) { return; } // We are in a context where only instance (or only static) methods are permitted. We reject the others. bool keepStatic = isImplicitReceiver && isStaticContext || Binder.IsMemberAccessedThroughType(receiverOpt); RemoveStaticInstanceMismatches(results, keepStatic); } private static void RemoveStaticInstanceMismatches<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, bool requireStatic) where TMember : Symbol { for (int f = 0; f < results.Count; ++f) { var result = results[f]; TMember member = result.Member; if (result.Result.IsValid && member.RequiresInstanceReceiver() == requireStatic) { results[f] = new MemberResolutionResult<TMember>(member, result.LeastOverriddenMember, MemberAnalysisResult.StaticInstanceMismatch()); } } } private static void RemoveMethodsNotDeclaredStatic<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results) where TMember : Symbol { // RemoveStaticInstanceMismatches allows methods that do not need a receiver but are not declared static, // such as a local function that is not declared static. This eliminates methods that are not actually // declared as static for (int f = 0; f < results.Count; f++) { var result = results[f]; TMember member = result.Member; if (result.Result.IsValid && !member.IsStatic) { results[f] = new MemberResolutionResult<TMember>(member, result.LeastOverriddenMember, MemberAnalysisResult.StaticInstanceMismatch()); } } } private void RemoveConstraintViolations<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, CompoundUseSiteInfo<AssemblySymbol> template) where TMember : Symbol { // When the feature 'ImprovedOverloadCandidates' is enabled, we do not include methods for which the type arguments // violate the constraints of the method's type parameters. // Constraint violations apply to method in a method group, not to properties in a "property group". if (typeof(TMember) != typeof(MethodSymbol)) { return; } for (int f = 0; f < results.Count; ++f) { var result = results[f]; var member = (MethodSymbol)(Symbol)result.Member; // a constraint failure on the method trumps (for reporting purposes) a previously-detected // constraint failure on the constructed type of a parameter if ((result.Result.IsValid || result.Result.Kind == MemberResolutionKind.ConstructedParameterFailedConstraintCheck) && FailsConstraintChecks(member, out ArrayBuilder<TypeParameterDiagnosticInfo> constraintFailureDiagnosticsOpt, template)) { results[f] = new MemberResolutionResult<TMember>( result.Member, result.LeastOverriddenMember, MemberAnalysisResult.ConstraintFailure(constraintFailureDiagnosticsOpt.ToImmutableAndFree())); } } } #nullable enable private void RemoveCallingConventionMismatches<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, in CallingConventionInfo expectedConvention) where TMember : Symbol { if (typeof(TMember) != typeof(MethodSymbol)) { return; } Debug.Assert(!expectedConvention.CallKind.HasUnknownCallingConventionAttributeBits()); Debug.Assert(expectedConvention.UnmanagedCallingConventionTypes is not null); Debug.Assert(expectedConvention.UnmanagedCallingConventionTypes.IsEmpty || expectedConvention.CallKind == Cci.CallingConvention.Unmanaged); Debug.Assert(!_binder.IsEarlyAttributeBinder); if (_binder.InAttributeArgument || (_binder.Flags & BinderFlags.InContextualAttributeBinder) != 0) { // We're at a location where the unmanaged data might not yet been bound. This cannot be valid code // anyway, as attribute arguments can't be method references, so we'll just assume that the conventions // match, as there will be other errors that supersede these anyway return; } for (int i = 0; i < results.Count; i++) { var result = results[i]; var member = (MethodSymbol)(Symbol)result.Member; if (result.Result.IsValid) { // We're not in an attribute, so cycles shouldn't be possible var unmanagedCallersOnlyData = member.GetUnmanagedCallersOnlyAttributeData(forceComplete: true); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound) && !ReferenceEquals(unmanagedCallersOnlyData, UnmanagedCallersOnlyAttributeData.Uninitialized)); Cci.CallingConvention actualCallKind; ImmutableHashSet<INamedTypeSymbolInternal> actualUnmanagedCallingConventionTypes; if (unmanagedCallersOnlyData is null) { actualCallKind = member.CallingConvention; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; } else { // There's data from an UnmanagedCallersOnlyAttribute present, which takes precedence over the // CallKind bit in the method definition. We use the following rules to decode the attribute: // * If no types are specified, the CallKind is treated as Unmanaged, with no unmanaged calling convention types // * If there is one type specified, and that type is named CallConvCdecl, CallConvThiscall, CallConvStdcall, or // CallConvFastcall, the CallKind is treated as CDecl, ThisCall, Standard, or FastCall, respectively, with no // calling types. // * If multiple types are specified or the single type is not named one of the specially called out types above, // the CallKind is treated as Unmanaged, with the union of the types specified treated as calling convention types. var unmanagedCallingConventionTypes = unmanagedCallersOnlyData.CallingConventionTypes; Debug.Assert(unmanagedCallingConventionTypes.All(u => FunctionPointerTypeSymbol.IsCallingConventionModifier((NamedTypeSymbol)u))); switch (unmanagedCallingConventionTypes.Count) { case 0: actualCallKind = Cci.CallingConvention.Unmanaged; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; case 1: switch (unmanagedCallingConventionTypes.Single().Name) { case "CallConvCdecl": actualCallKind = Cci.CallingConvention.CDecl; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; case "CallConvStdcall": actualCallKind = Cci.CallingConvention.Standard; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; case "CallConvThiscall": actualCallKind = Cci.CallingConvention.ThisCall; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; case "CallConvFastcall": actualCallKind = Cci.CallingConvention.FastCall; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; default: goto outerDefault; } break; default: outerDefault: actualCallKind = Cci.CallingConvention.Unmanaged; actualUnmanagedCallingConventionTypes = unmanagedCallingConventionTypes; break; } } // The rules for matching a calling convention are: // 1. The CallKinds must match exactly // 2. If the CallKind is Unmanaged, then the set of calling convention types must match exactly, ignoring order // and duplicates. We already have both sets in a HashSet, so we can just ensure they're the same length and // that everything from one set is in the other set. if (actualCallKind.HasUnknownCallingConventionAttributeBits() || !actualCallKind.IsCallingConvention(expectedConvention.CallKind)) { results[i] = makeWrongCallingConvention(result); continue; } if (expectedConvention.CallKind.IsCallingConvention(Cci.CallingConvention.Unmanaged)) { if (expectedConvention.UnmanagedCallingConventionTypes.Count != actualUnmanagedCallingConventionTypes.Count) { results[i] = makeWrongCallingConvention(result); continue; } foreach (var expectedModifier in expectedConvention.UnmanagedCallingConventionTypes) { if (!actualUnmanagedCallingConventionTypes.Contains(((CSharpCustomModifier)expectedModifier).ModifierSymbol)) { results[i] = makeWrongCallingConvention(result); break; } } } } } static MemberResolutionResult<TMember> makeWrongCallingConvention(MemberResolutionResult<TMember> result) => new MemberResolutionResult<TMember>(result.Member, result.LeastOverriddenMember, MemberAnalysisResult.WrongCallingConvention()); } #nullable disable private bool FailsConstraintChecks(MethodSymbol method, out ArrayBuilder<TypeParameterDiagnosticInfo> constraintFailureDiagnosticsOpt, CompoundUseSiteInfo<AssemblySymbol> template) { if (method.Arity == 0 || method.OriginalDefinition == (object)method) { constraintFailureDiagnosticsOpt = null; return false; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null; bool constraintsSatisfied = ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, location: NoLocation.Singleton, diagnostics: null, template), diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt: null, ref useSiteDiagnosticsBuilder); if (!constraintsSatisfied) { if (useSiteDiagnosticsBuilder != null) { diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder); useSiteDiagnosticsBuilder.Free(); } constraintFailureDiagnosticsOpt = diagnosticsBuilder; return true; } diagnosticsBuilder.Free(); useSiteDiagnosticsBuilder?.Free(); constraintFailureDiagnosticsOpt = null; return false; } /// <summary> /// Remove candidates to a delegate conversion where the method's return ref kind or return type is wrong. /// </summary> /// <param name="returnRefKind">The ref kind of the delegate's return, if known. This is only unknown in /// error scenarios, such as a delegate type that has no invoke method.</param> /// <param name="returnType">The return type of the delegate, if known. It isn't /// known when we're attempting to infer the return type of a method group for type inference.</param> private void RemoveDelegateConversionsWithWrongReturnType<TMember>( ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, RefKind? returnRefKind, TypeSymbol returnType, bool isFunctionPointerConversion) where TMember : Symbol { // When the feature 'ImprovedOverloadCandidates' is enabled, then a delegate conversion overload resolution // rejects candidates that have the wrong return ref kind or return type. // Delegate conversions apply to method in a method group, not to properties in a "property group". Debug.Assert(typeof(TMember) == typeof(MethodSymbol)); for (int f = 0; f < results.Count; ++f) { var result = results[f]; if (!result.Result.IsValid) { continue; } var method = (MethodSymbol)(Symbol)result.Member; bool returnsMatch; if (returnType is null || method.ReturnType.Equals(returnType, TypeCompareKind.AllIgnoreOptions)) { returnsMatch = true; } else if (returnRefKind == RefKind.None) { returnsMatch = Conversions.HasIdentityOrImplicitReferenceConversion(method.ReturnType, returnType, ref useSiteInfo); if (!returnsMatch && isFunctionPointerConversion) { returnsMatch = ConversionsBase.HasImplicitPointerToVoidConversion(method.ReturnType, returnType) || Conversions.HasImplicitPointerConversion(method.ReturnType, returnType, ref useSiteInfo); } } else { returnsMatch = false; } if (!returnsMatch) { results[f] = new MemberResolutionResult<TMember>( result.Member, result.LeastOverriddenMember, MemberAnalysisResult.WrongReturnType()); } else if (method.RefKind != returnRefKind) { results[f] = new MemberResolutionResult<TMember>( result.Member, result.LeastOverriddenMember, MemberAnalysisResult.WrongRefKind()); } } } private static Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> PartitionMembersByContainingType<TMember>(ArrayBuilder<TMember> members) where TMember : Symbol { Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMap = new Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>>(); for (int i = 0; i < members.Count; i++) { TMember member = members[i]; NamedTypeSymbol containingType = member.ContainingType; ArrayBuilder<TMember> builder; if (!containingTypeMap.TryGetValue(containingType, out builder)) { builder = ArrayBuilder<TMember>.GetInstance(); containingTypeMap[containingType] = builder; } builder.Add(member); } return containingTypeMap; } private static void ClearContainingTypeMap<TMember>(ref Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt) where TMember : Symbol { if ((object)containingTypeMapOpt != null) { foreach (ArrayBuilder<TMember> builder in containingTypeMapOpt.Values) { builder.Free(); } containingTypeMapOpt = null; } } private void AddConstructorToCandidateSet(MethodSymbol constructor, ArrayBuilder<MemberResolutionResult<MethodSymbol>> results, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Filter out constructors with unsupported metadata. if (constructor.HasUnsupportedMetadata) { Debug.Assert(!MemberAnalysisResult.UnsupportedMetadata().HasUseSiteDiagnosticToReportFor(constructor)); if (completeResults) { results.Add(new MemberResolutionResult<MethodSymbol>(constructor, constructor, MemberAnalysisResult.UnsupportedMetadata())); } return; } var normalResult = IsConstructorApplicableInNormalForm(constructor, arguments, completeResults, ref useSiteInfo); var result = normalResult; if (!normalResult.IsValid) { if (IsValidParams(constructor)) { var expandedResult = IsConstructorApplicableInExpandedForm(constructor, arguments, completeResults, ref useSiteInfo); if (expandedResult.IsValid || completeResults) { result = expandedResult; } } } // If the constructor has a use site diagnostic, we don't want to discard it because we'll have to report the diagnostic later. if (result.IsValid || completeResults || result.HasUseSiteDiagnosticToReportFor(constructor)) { results.Add(new MemberResolutionResult<MethodSymbol>(constructor, constructor, result)); } } private MemberAnalysisResult IsConstructorApplicableInNormalForm( MethodSymbol constructor, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var argumentAnalysis = AnalyzeArguments(constructor, arguments, isMethodGroupConversion: false, expanded: false); // Constructors are never involved in method group conversion. if (!argumentAnalysis.IsValid) { return MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis); } // Check after argument analysis, but before more complicated type inference and argument type validation. if (constructor.HasUseSiteError) { return MemberAnalysisResult.UseSiteError(); } var effectiveParameters = GetEffectiveParametersInNormalForm( constructor, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments: false); return IsApplicable( constructor, effectiveParameters, arguments, argumentAnalysis.ArgsToParamsOpt, isVararg: constructor.IsVararg, hasAnyRefOmittedArgument: false, ignoreOpenTypes: false, completeResults: completeResults, useSiteInfo: ref useSiteInfo); } private MemberAnalysisResult IsConstructorApplicableInExpandedForm( MethodSymbol constructor, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var argumentAnalysis = AnalyzeArguments(constructor, arguments, isMethodGroupConversion: false, expanded: true); if (!argumentAnalysis.IsValid) { return MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis); } // Check after argument analysis, but before more complicated type inference and argument type validation. if (constructor.HasUseSiteError) { return MemberAnalysisResult.UseSiteError(); } var effectiveParameters = GetEffectiveParametersInExpandedForm( constructor, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments: false); // A vararg ctor is never applicable in its expanded form because // it is never a params method. Debug.Assert(!constructor.IsVararg); var result = IsApplicable( constructor, effectiveParameters, arguments, argumentAnalysis.ArgsToParamsOpt, isVararg: false, hasAnyRefOmittedArgument: false, ignoreOpenTypes: false, completeResults: completeResults, useSiteInfo: ref useSiteInfo); return result.IsValid ? MemberAnalysisResult.ExpandedForm(result.ArgsToParamsOpt, result.ConversionsOpt, hasAnyRefOmittedArgument: false) : result; } private void AddMemberToCandidateSet<TMember>( TMember member, // method or property ArrayBuilder<MemberResolutionResult<TMember>> results, ArrayBuilder<TMember> members, ArrayBuilder<TypeWithAnnotations> typeArguments, BoundExpression receiverOpt, AnalyzedArguments arguments, bool completeResults, bool isMethodGroupConversion, bool allowRefOmittedArguments, Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt, bool inferWithDynamic, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowUnexpandedForm) where TMember : Symbol { // SPEC VIOLATION: // // The specification states that the method group that resulted from member lookup has // already had all the "override" methods removed; according to the spec, only the // original declaring type declarations remain. // // However, for IDE purposes ("go to definition") we *want* member lookup and overload // resolution to identify the overriding method. And the same for the purposes of code // generation. (For example, if you have 123.ToString() then we want to make a call to // Int32.ToString() directly, passing the int, rather than boxing and calling // Object.ToString() on the boxed object.) // // Therefore, in member lookup we do *not* eliminate the "override" methods, even though // the spec says to. When overload resolution is handed a method group, it contains both // the overriding methods and the overridden methods. // // This is bad; it means that we're going to be doing a lot of extra work. We don't need // to analyze every overload of every method to determine if it is applicable; we // already know that if one of them is applicable then they all will be. And we don't // want to be in a situation where we're comparing two identical methods for which is // "better" either. // // What we'll do here is first eliminate all the "duplicate" overriding methods. // However, because we want to give the result as the more derived method, we'll do the // opposite of what the member lookup spec says; we'll eliminate the less-derived // methods, not the more-derived overrides. This means that we'll have to be a bit more // clever in filtering out methods from less-derived classes later, but we'll cross that // bridge when we come to it. if (members.Count < 2) { // No hiding or overriding possible. } else if (containingTypeMapOpt == null) { if (MemberGroupContainsMoreDerivedOverride(members, member, checkOverrideContainingType: true, ref useSiteInfo)) { // Don't even add it to the result set. We'll add only the most-overriding members. return; } if (MemberGroupHidesByName(members, member, ref useSiteInfo)) { return; } } else if (containingTypeMapOpt.Count == 1) { // No hiding or overriding since all members are in the same type. } else { // NOTE: only check for overriding/hiding in subtypes of f.ContainingType. NamedTypeSymbol memberContainingType = member.ContainingType; foreach (var pair in containingTypeMapOpt) { NamedTypeSymbol otherType = pair.Key; if (otherType.IsDerivedFrom(memberContainingType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo)) { ArrayBuilder<TMember> others = pair.Value; if (MemberGroupContainsMoreDerivedOverride(others, member, checkOverrideContainingType: false, ref useSiteInfo)) { // Don't even add it to the result set. We'll add only the most-overriding members. return; } if (MemberGroupHidesByName(others, member, ref useSiteInfo)) { return; } } } } var leastOverriddenMember = (TMember)member.GetLeastOverriddenMember(_binder.ContainingType); // Filter out members with unsupported metadata. if (member.HasUnsupportedMetadata) { Debug.Assert(!MemberAnalysisResult.UnsupportedMetadata().HasUseSiteDiagnosticToReportFor(member)); if (completeResults) { results.Add(new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UnsupportedMetadata())); } return; } // First deal with eliminating generic-arity mismatches. // SPEC: If F is generic and M includes a type argument list, F is a candidate when: // SPEC: * F has the same number of method type parameters as were supplied in the type argument list, and // // This is specifying an impossible condition; the member lookup algorithm has already filtered // out methods from the method group that have the wrong generic arity. Debug.Assert(typeArguments.Count == 0 || typeArguments.Count == member.GetMemberArity()); // Second, we need to determine if the method is applicable in its normal form or its expanded form. var normalResult = (allowUnexpandedForm || !IsValidParams(leastOverriddenMember)) ? IsMemberApplicableInNormalForm( member, leastOverriddenMember, typeArguments, arguments, isMethodGroupConversion: isMethodGroupConversion, allowRefOmittedArguments: allowRefOmittedArguments, inferWithDynamic: inferWithDynamic, completeResults: completeResults, useSiteInfo: ref useSiteInfo) : default(MemberResolutionResult<TMember>); var result = normalResult; if (!normalResult.Result.IsValid) { // Whether a virtual method [indexer] is a "params" method [indexer] or not depends solely on how the // *original* declaration was declared. There are a variety of C# or MSIL // tricks you can pull to make overriding methods [indexers] inconsistent with overridden // methods [indexers] (or implementing methods [indexers] inconsistent with interfaces). if (!isMethodGroupConversion && IsValidParams(leastOverriddenMember)) { var expandedResult = IsMemberApplicableInExpandedForm( member, leastOverriddenMember, typeArguments, arguments, allowRefOmittedArguments: allowRefOmittedArguments, completeResults: completeResults, useSiteInfo: ref useSiteInfo); if (PreferExpandedFormOverNormalForm(normalResult.Result, expandedResult.Result)) { result = expandedResult; } } } // Retain candidates with use site diagnostics for later reporting. if (result.Result.IsValid || completeResults || result.HasUseSiteDiagnosticToReport) { results.Add(result); } else { result.Member.AddUseSiteInfo(ref useSiteInfo, addDiagnostics: false); } } // If the normal form is invalid and the expanded form is valid then obviously we prefer // the expanded form. However, there may be error-reporting situations where we // prefer to report the error on the expanded form rather than the normal form. // For example, if you have something like Goo<T>(params T[]) and a call // Goo(1, "") then the error for the normal form is "too many arguments" // and the error for the expanded form is "failed to infer T". Clearly the // expanded form error is better. private static bool PreferExpandedFormOverNormalForm(MemberAnalysisResult normalResult, MemberAnalysisResult expandedResult) { Debug.Assert(!normalResult.IsValid); if (expandedResult.IsValid) { return true; } switch (normalResult.Kind) { case MemberResolutionKind.RequiredParameterMissing: case MemberResolutionKind.NoCorrespondingParameter: switch (expandedResult.Kind) { case MemberResolutionKind.BadArgumentConversion: case MemberResolutionKind.NameUsedForPositional: case MemberResolutionKind.TypeInferenceFailed: case MemberResolutionKind.TypeInferenceExtensionInstanceArgument: case MemberResolutionKind.ConstructedParameterFailedConstraintCheck: case MemberResolutionKind.NoCorrespondingNamedParameter: case MemberResolutionKind.UseSiteError: case MemberResolutionKind.BadNonTrailingNamedArgument: case MemberResolutionKind.DuplicateNamedArgument: return true; } break; } return false; } // We need to know if this is a valid formal parameter list with a parameter array // as the final formal parameter. We might be in an error recovery scenario // where the params array is not an array type. public static bool IsValidParams(Symbol member) { // A varargs method is never a valid params method. if (member.GetIsVararg()) { return false; } int paramCount = member.GetParameterCount(); if (paramCount == 0) { return false; } ParameterSymbol final = member.GetParameters().Last(); return IsValidParamsParameter(final); } public static bool IsValidParamsParameter(ParameterSymbol final) { Debug.Assert((object)final == final.ContainingSymbol.GetParameters().Last()); return final.IsParams && ((ParameterSymbol)final.OriginalDefinition).Type.IsSZArray(); } /// <summary> /// Does <paramref name="moreDerivedOverride"/> override <paramref name="member"/> or the /// thing that it originally overrides, but in a more derived class? /// </summary> /// <param name="checkOverrideContainingType">Set to false if the caller has already checked that /// <paramref name="moreDerivedOverride"/> is in a type that derives from the type containing /// <paramref name="member"/>.</param> private static bool IsMoreDerivedOverride( Symbol member, Symbol moreDerivedOverride, bool checkOverrideContainingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!moreDerivedOverride.IsOverride || checkOverrideContainingType && !moreDerivedOverride.ContainingType.IsDerivedFrom(member.ContainingType, TypeCompareKind.ConsiderEverything, ref useSiteInfo) || !MemberSignatureComparer.SloppyOverrideComparer.Equals(member, moreDerivedOverride)) { // Easy out. return false; } // Rather than following the member.GetOverriddenMember() chain, we check to see if both // methods ultimately override the same original method. This addresses issues in binary compat // scenarios where the override chain may skip some steps. // See https://github.com/dotnet/roslyn/issues/45798 for an example. return moreDerivedOverride.GetLeastOverriddenMember(accessingTypeOpt: null).OriginalDefinition == member.GetLeastOverriddenMember(accessingTypeOpt: null).OriginalDefinition; } /// <summary> /// Does the member group <paramref name="members"/> contain an override of <paramref name="member"/> or the method it /// overrides, but in a more derived type? /// </summary> /// <param name="checkOverrideContainingType">Set to false if the caller has already checked that /// <paramref name="members"/> are all in a type that derives from the type containing /// <paramref name="member"/>.</param> private static bool MemberGroupContainsMoreDerivedOverride<TMember>( ArrayBuilder<TMember> members, TMember member, bool checkOverrideContainingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { if (!member.IsVirtual && !member.IsAbstract && !member.IsOverride) { return false; } if (!member.ContainingType.IsClassType()) { return false; } for (var i = 0; i < members.Count; ++i) { if (IsMoreDerivedOverride(member: member, moreDerivedOverride: members[i], checkOverrideContainingType: checkOverrideContainingType, ref useSiteInfo)) { return true; } } return false; } private static bool MemberGroupHidesByName<TMember>(ArrayBuilder<TMember> members, TMember member, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { NamedTypeSymbol memberContainingType = member.ContainingType; foreach (var otherMember in members) { NamedTypeSymbol otherContainingType = otherMember.ContainingType; if (HidesByName(otherMember) && otherContainingType.IsDerivedFrom(memberContainingType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo)) { return true; } } return false; } /// <remarks> /// This is specifically a private helper function (rather than a public property or extension method) /// because applying this predicate to a non-method member doesn't have a clear meaning. The goal was /// simply to avoid repeating ad-hoc code in a group of related collections. /// </remarks> private static bool HidesByName(Symbol member) { switch (member.Kind) { case SymbolKind.Method: return ((MethodSymbol)member).HidesBaseMethodsByName; case SymbolKind.Property: return ((PropertySymbol)member).HidesBasePropertiesByName; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private void RemoveInaccessibleTypeArguments<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { for (int f = 0; f < results.Count; ++f) { var result = results[f]; if (result.Result.IsValid && !TypeArgumentsAccessible(result.Member.GetMemberTypeArgumentsNoUseSiteDiagnostics(), ref useSiteInfo)) { results[f] = new MemberResolutionResult<TMember>(result.Member, result.LeastOverriddenMember, MemberAnalysisResult.InaccessibleTypeArgument()); } } } private bool TypeArgumentsAccessible(ImmutableArray<TypeSymbol> typeArguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { foreach (TypeSymbol arg in typeArguments) { if (!_binder.IsAccessible(arg, ref useSiteInfo)) return false; } return true; } private static void RemoveLessDerivedMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { // 7.6.5.1 Method invocations // SPEC: For each method C.F in the set, where C is the type in which the method F is declared, // SPEC: all methods declared in a base type of C are removed from the set. Furthermore, if C // SPEC: is a class type other than object, all methods declared in an interface type are removed // SPEC: from the set. (This latter rule only has affect when the method group was the result of // SPEC: a member lookup on a type parameter having an effective base class other than object // SPEC: and a non-empty effective interface set.) // This is going to get a bit complicated. // // Call the "original declaring type" of a method the type which first declares the // method, rather than overriding it. // // The specification states that the method group that resulted from member lookup has // already had all the "override" methods removed; according to the spec, only the // original declaring type declarations remain. This means that when we do this // filtering, we're not suppose to remove methods of a base class just because there was // some override in a more derived class. Whether there is an override or not is an // implementation detail of the derived class; it shouldn't affect overload resolution. // The point of overload resolution is to determine the *slot* that is going to be // invoked, not the specific overriding method body. // // However, for IDE purposes ("go to definition") we *want* member lookup and overload // resolution to identify the overriding method. And the same for the purposes of code // generation. (For example, if you have 123.ToString() then we want to make a call to // Int32.ToString() directly, passing the int, rather than boxing and calling // Object.ToString() on the boxed object.) // // Therefore, in member lookup we do *not* eliminate the "override" methods, even though // the spec says to. When overload resolution is handed a method group, it contains both // the overriding methods and the overridden methods. We eliminate the *overridden* // methods during applicable candidate set construction. // // Let's look at an example. Suppose we have in the method group: // // virtual Animal.M(T1), // virtual Mammal.M(T2), // virtual Mammal.M(T3), // override Giraffe.M(T1), // override Giraffe.M(T2) // // According to the spec, the override methods should not even be there. But they are. // // When we constructed the applicable candidate set we already removed everything that // was less-overridden. So the applicable candidate set contains: // // virtual Mammal.M(T3), // override Giraffe.M(T1), // override Giraffe.M(T2) // // Again, that is not what should be there; what should be there are the three non- // overriding methods. For the purposes of removing more stuff, we need to behave as // though that's what was there. // // The presence of Giraffe.M(T2) does *not* justify the removal of Mammal.M(T3); it is // not to be considered a method of Giraffe, but rather a method of Mammal for the // purposes of removing other methods. // // However, the presence of Mammal.M(T3) does justify the removal of Giraffe.M(T1). Why? // Because the presence of Mammal.M(T3) justifies the removal of Animal.M(T1), and that // is what is supposed to be in the set instead of Giraffe.M(T1). // // The resulting candidate set after the filtering according to the spec should be: // // virtual Mammal.M(T3), virtual Mammal.M(T2) // // But what we actually want to be there is: // // virtual Mammal.M(T3), override Giraffe.M(T2) // // So that a "go to definition" (should the latter be chosen as best) goes to the override. // // OK, so what are we going to do here? // // First, deal with this business about object and interfaces. RemoveAllInterfaceMembers(results); // Second, apply the rule that we eliminate any method whose *original declaring type* // is a base type of the original declaring type of any other method. // Note that this (and several of the other algorithms in overload resolution) is // O(n^2). (We expect that n will be relatively small. Also, we're trying to do these // algorithms without allocating hardly any additional memory, which pushes us towards // walking data structures multiple times rather than caching information about them.) for (int f = 0; f < results.Count; ++f) { var result = results[f]; // As in dev12, we want to drop use site errors from less-derived types. // NOTE: Because of use site warnings, a result with a diagnostic to report // might not have kind UseSiteError. This could result in a kind being // switched to LessDerived (i.e. loss of information), but it is the most // straightforward way to suppress use site diagnostics from less-derived // members. if (!(result.Result.IsValid || result.HasUseSiteDiagnosticToReport)) { continue; } // Note that we are doing something which appears a bit dodgy here: we're modifying // the validity of elements of the set while inside an outer loop which is filtering // the set based on validity. This means that we could remove an item from the set // that we ought to be processing later. However, because the "is a base type of" // relationship is transitive, that's OK. For example, suppose we have members // Cat.M, Mammal.M and Animal.M in the set. The first time through the outer loop we // eliminate Mammal.M and Animal.M, and therefore we never process Mammal.M the // second time through the outer loop. That's OK, because we have already done the // work necessary to eliminate methods on base types of Mammal when we eliminated // methods on base types of Cat. if (IsLessDerivedThanAny(result.LeastOverriddenMember.ContainingType, results, ref useSiteInfo)) { results[f] = new MemberResolutionResult<TMember>(result.Member, result.LeastOverriddenMember, MemberAnalysisResult.LessDerived()); } } } // Is this type a base type of any valid method on the list? private static bool IsLessDerivedThanAny<TMember>(TypeSymbol type, ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { for (int f = 0; f < results.Count; ++f) { var result = results[f]; if (!result.Result.IsValid) { continue; } var currentType = result.LeastOverriddenMember.ContainingType; // For purposes of removing less-derived methods, object is considered to be a base // type of any type other than itself. // UNDONE: Do we also need to special-case System.Array being a base type of array, // and so on? if (type.SpecialType == SpecialType.System_Object && currentType.SpecialType != SpecialType.System_Object) { return true; } if (currentType.IsInterfaceType() && type.IsInterfaceType() && currentType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).Contains((NamedTypeSymbol)type)) { return true; } else if (currentType.IsClassType() && type.IsClassType() && currentType.IsDerivedFrom(type, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo)) { return true; } } return false; } private static void RemoveAllInterfaceMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results) where TMember : Symbol { // Consider the following case: // // interface IGoo { string ToString(); } // class C { public override string ToString() { whatever } } // class D : C, IGoo // { // public override string ToString() { whatever } // string IGoo.ToString() { whatever } // } // ... // void M<U>(U u) where U : C, IGoo { u.ToString(); } // ??? // ... // M(new D()); // // What should overload resolution do on the call to u.ToString()? // // We will have IGoo.ToString and C.ToString (which is an override of object.ToString) // in the candidate set. Does the rule apply to eliminate all interface methods? NO. The // rule only applies if the candidate set contains a method which originally came from a // class type other than object. The method C.ToString is the "slot" for // object.ToString, so this counts as coming from object. M should call the explicit // interface implementation. // // If, by contrast, that said // // class C { public new virtual string ToString() { whatever } } // // Then the candidate set contains a method ToString which comes from a class type other // than object. The interface method should be eliminated and M should call virtual // method C.ToString(). bool anyClassOtherThanObject = false; for (int f = 0; f < results.Count; f++) { var result = results[f]; if (!result.Result.IsValid) { continue; } var type = result.LeastOverriddenMember.ContainingType; if (type.IsClassType() && type.GetSpecialTypeSafe() != SpecialType.System_Object) { anyClassOtherThanObject = true; break; } } if (!anyClassOtherThanObject) { return; } for (int f = 0; f < results.Count; f++) { var result = results[f]; if (!result.Result.IsValid) { continue; } var member = result.Member; if (member.ContainingType.IsInterfaceType()) { results[f] = new MemberResolutionResult<TMember>(member, result.LeastOverriddenMember, MemberAnalysisResult.LessDerived()); } } } // Perform instance constructor overload resolution, storing the results into "results". If // completeResults is false, then invalid results don't have to be stored. The results will // still contain all possible successful resolution. private void PerformObjectCreationOverloadResolution( ArrayBuilder<MemberResolutionResult<MethodSymbol>> results, ImmutableArray<MethodSymbol> constructors, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The instance constructor to invoke is determined using the overload resolution // SPEC: rules of 7.5.3. The set of candidate instance constructors consists of all // SPEC: accessible instance constructors declared in T which are applicable with respect // SPEC: to A (7.5.3.1). If the set of candidate instance constructors is empty, or if a // SPEC: single best instance constructor cannot be identified, a binding-time error occurs. foreach (MethodSymbol constructor in constructors) { AddConstructorToCandidateSet(constructor, results, arguments, completeResults, ref useSiteInfo); } ReportUseSiteInfo(results, ref useSiteInfo); // The best method of the set of candidate methods is identified. If a single best // method cannot be identified, the method invocation is ambiguous, and a binding-time // error occurs. RemoveWorseMembers(results, arguments, ref useSiteInfo); return; } private static void ReportUseSiteInfo<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { foreach (MemberResolutionResult<TMember> result in results) { result.Member.AddUseSiteInfo(ref useSiteInfo, addDiagnostics: result.HasUseSiteDiagnosticToReport); } } private int GetTheBestCandidateIndex<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, AnalyzedArguments arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { int currentBestIndex = -1; for (int index = 0; index < results.Count; index++) { if (!results[index].IsValid) { continue; } // Assume that the current candidate is the best if we don't have any if (currentBestIndex == -1) { currentBestIndex = index; } else if (results[currentBestIndex].Member == results[index].Member) { currentBestIndex = -1; } else { var better = BetterFunctionMember(results[currentBestIndex], results[index], arguments.Arguments, ref useSiteInfo); if (better == BetterResult.Right) { // The current best is worse currentBestIndex = index; } else if (better != BetterResult.Left) { // The current best is not better currentBestIndex = -1; } } } // Make sure that every candidate up to the current best is worse for (int index = 0; index < currentBestIndex; index++) { if (!results[index].IsValid) { continue; } if (results[currentBestIndex].Member == results[index].Member) { return -1; } var better = BetterFunctionMember(results[currentBestIndex], results[index], arguments.Arguments, ref useSiteInfo); if (better != BetterResult.Left) { // The current best is not better return -1; } } return currentBestIndex; } private void RemoveWorseMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, AnalyzedArguments arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { // SPEC: Given the set of applicable candidate function members, the best function member in // SPEC: that set is located. Otherwise, the best function member is the one function member // SPEC: that is better than all other function members with respect to the given argument // SPEC: list. // Note that the above rules require that the best member be *better* than all other // applicable candidates. Consider three overloads such that: // // 3 beats 2 // 2 beats 1 // 3 is neither better than nor worse than 1 // // It is tempting to say that overload 3 is the winner because it is the one method // that beats something, and is beaten by nothing. But that would be incorrect; // method 3 needs to beat all other methods, including method 1. // // We work up a full analysis of every member of the set. If it is worse than anything // then we need to do no more work; we know it cannot win. But it is also possible that // it is not worse than anything but not better than everything. if (SingleValidResult(results)) { return; } // See if we have a winner, otherwise we might need to perform additional analysis // in order to improve diagnostics int bestIndex = GetTheBestCandidateIndex(results, arguments, ref useSiteInfo); if (bestIndex != -1) { // Mark all other candidates as worse for (int index = 0; index < results.Count; index++) { if (results[index].IsValid && index != bestIndex) { results[index] = results[index].Worse(); } } return; } const int unknown = 0; const int worseThanSomething = 1; const int notBetterThanEverything = 2; var worse = ArrayBuilder<int>.GetInstance(results.Count, unknown); int countOfNotBestCandidates = 0; int notBestIdx = -1; for (int c1Idx = 0; c1Idx < results.Count; c1Idx++) { var c1Result = results[c1Idx]; // If we already know this is worse than something else, no need to check again. if (!c1Result.IsValid || worse[c1Idx] == worseThanSomething) { continue; } for (int c2Idx = 0; c2Idx < results.Count; c2Idx++) { var c2Result = results[c2Idx]; if (!c2Result.IsValid || c1Idx == c2Idx || c1Result.Member == c2Result.Member) { continue; } var better = BetterFunctionMember(c1Result, c2Result, arguments.Arguments, ref useSiteInfo); if (better == BetterResult.Left) { worse[c2Idx] = worseThanSomething; } else if (better == BetterResult.Right) { worse[c1Idx] = worseThanSomething; break; } } if (worse[c1Idx] == unknown) { // c1 was not worse than anything worse[c1Idx] = notBetterThanEverything; countOfNotBestCandidates++; notBestIdx = c1Idx; } } if (countOfNotBestCandidates == 0) { for (int i = 0; i < worse.Count; ++i) { Debug.Assert(!results[i].IsValid || worse[i] != unknown); if (worse[i] == worseThanSomething) { results[i] = results[i].Worse(); } } } else if (countOfNotBestCandidates == 1) { for (int i = 0; i < worse.Count; ++i) { Debug.Assert(!results[i].IsValid || worse[i] != unknown); if (worse[i] == worseThanSomething) { // Mark those candidates, that are worse than the single notBest candidate, as Worst in order to improve error reporting. results[i] = BetterResult.Left == BetterFunctionMember(results[notBestIdx], results[i], arguments.Arguments, ref useSiteInfo) ? results[i].Worst() : results[i].Worse(); } else { Debug.Assert(worse[i] != notBetterThanEverything || i == notBestIdx); } } Debug.Assert(worse[notBestIdx] == notBetterThanEverything); results[notBestIdx] = results[notBestIdx].Worse(); } else { Debug.Assert(countOfNotBestCandidates > 1); for (int i = 0; i < worse.Count; ++i) { Debug.Assert(!results[i].IsValid || worse[i] != unknown); if (worse[i] == worseThanSomething) { // Mark those candidates, that are worse than something, as Worst in order to improve error reporting. results[i] = results[i].Worst(); } else if (worse[i] == notBetterThanEverything) { results[i] = results[i].Worse(); } } } worse.Free(); } // Merge upstream/dev15.6.x #if false // Return the parameter type corresponding to the given argument index. private TypeSymbol GetParameterType(int argIndex, MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters) { RefKind discarded; return GetParameterType(argIndex, result, parameters, out discarded); } // Return the parameter type corresponding to the given argument index. private TypeSymbol GetParameterType(int argIndex, MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, out RefKind refKind) { int paramIndex = result.ParameterFromArgument(argIndex); ParameterSymbol parameter = parameters[paramIndex]; refKind = parameter.RefKind; var type = _binder.GetTypeOrReturnTypeWithAdjustedNullableAnnotations(parameter).TypeSymbol; #endif /// <summary> /// Returns the parameter type (considering params). /// </summary> private TypeSymbol GetParameterType(ParameterSymbol parameter, MemberAnalysisResult result) { var type = parameter.Type; if (result.Kind == MemberResolutionKind.ApplicableInExpandedForm && parameter.IsParams && type.IsSZArray()) { return ((ArrayTypeSymbol)type).ElementType; } else { return type; } } /// <summary> /// Returns the parameter corresponding to the given argument index. /// </summary> private static ParameterSymbol GetParameter(int argIndex, MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters) { int paramIndex = result.ParameterFromArgument(argIndex); return parameters[paramIndex]; } private BetterResult BetterFunctionMember<TMember>( MemberResolutionResult<TMember> m1, MemberResolutionResult<TMember> m2, ArrayBuilder<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { Debug.Assert(m1.Result.IsValid); Debug.Assert(m2.Result.IsValid); Debug.Assert(arguments != null); // Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method/property on an instance of a COM imported type. // We should have ignored the 'ref' on the parameter while determining the applicability of argument for the given method call. // As per Devdiv Bug #696573: '[Interop] Com omit ref overload resolution is incorrect', we must prefer non-ref omitted methods over ref omitted methods // when determining the BetterFunctionMember. // During argument rewriting, we will replace the argument value with a temporary local and pass that local by reference. bool hasAnyRefOmittedArgument1 = m1.Result.HasAnyRefOmittedArgument; bool hasAnyRefOmittedArgument2 = m2.Result.HasAnyRefOmittedArgument; if (hasAnyRefOmittedArgument1 != hasAnyRefOmittedArgument2) { return hasAnyRefOmittedArgument1 ? BetterResult.Right : BetterResult.Left; } else { return BetterFunctionMember(m1, m2, arguments, considerRefKinds: hasAnyRefOmittedArgument1, useSiteInfo: ref useSiteInfo); } } private BetterResult BetterFunctionMember<TMember>( MemberResolutionResult<TMember> m1, MemberResolutionResult<TMember> m2, ArrayBuilder<BoundExpression> arguments, bool considerRefKinds, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { Debug.Assert(m1.Result.IsValid); Debug.Assert(m2.Result.IsValid); Debug.Assert(arguments != null); // SPEC: // Parameter lists for each of the candidate function members are constructed in the following way: // The expanded form is used if the function member was applicable only in the expanded form. // Optional parameters with no corresponding arguments are removed from the parameter list // The parameters are reordered so that they occur at the same position as the corresponding argument in the argument list. // We don't actually create these lists, for efficiency reason. But we iterate over the arguments // and get the correspond parameter types. BetterResult result = BetterResult.Neither; bool okToDowngradeResultToNeither = false; bool ignoreDowngradableToNeither = false; // Given an argument list A with a set of argument expressions { E1, E2, ..., EN } and two // applicable function members MP and MQ with parameter types { P1, P2, ..., PN } and { Q1, Q2, ..., QN }, // MP is defined to be a better function member than MQ if // for each argument, the implicit conversion from EX to QX is not better than the // implicit conversion from EX to PX, and for at least one argument, the conversion from // EX to PX is better than the conversion from EX to QX. var m1LeastOverriddenParameters = m1.LeastOverriddenMember.GetParameters(); var m2LeastOverriddenParameters = m2.LeastOverriddenMember.GetParameters(); bool allSame = true; // Are all parameter types equivalent by identify conversions, ignoring Task-like differences? int i; for (i = 0; i < arguments.Count; ++i) { var argumentKind = arguments[i].Kind; // If these are both applicable varargs methods and we're looking at the __arglist argument // then clearly neither of them is going to be better in this argument. if (argumentKind == BoundKind.ArgListOperator) { Debug.Assert(i == arguments.Count - 1); Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg()); continue; } var parameter1 = GetParameter(i, m1.Result, m1LeastOverriddenParameters); var type1 = GetParameterType(parameter1, m1.Result); var parameter2 = GetParameter(i, m2.Result, m2LeastOverriddenParameters); var type2 = GetParameterType(parameter2, m2.Result); bool okToDowngradeToNeither; BetterResult r; r = BetterConversionFromExpression(arguments[i], type1, m1.Result.ConversionForArg(i), parameter1.RefKind, type2, m2.Result.ConversionForArg(i), parameter2.RefKind, considerRefKinds, ref useSiteInfo, out okToDowngradeToNeither); var type1Normalized = type1; var type2Normalized = type2; // Normalizing task types can cause attributes to be bound on the type, // and attribute arguments may call overloaded methods in error cases. // To avoid a stack overflow, we must not normalize task types within attribute arguments. if (!_binder.InAttributeArgument) { type1Normalized = type1.NormalizeTaskTypes(Compilation); type2Normalized = type2.NormalizeTaskTypes(Compilation); } if (r == BetterResult.Neither) { if (allSame && Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, ref useSiteInfo).Kind != ConversionKind.Identity) { allSame = false; } // We learned nothing from this one. Keep going. continue; } if (Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, ref useSiteInfo).Kind != ConversionKind.Identity) { allSame = false; } // One of them was better, even if identical up to Task-likeness. Does that contradict a previous result or add a new fact? if (result == BetterResult.Neither) { if (!(ignoreDowngradableToNeither && okToDowngradeToNeither)) { // Add a new fact; we know that one of them is better when we didn't know that before. result = r; okToDowngradeResultToNeither = okToDowngradeToNeither; } } else if (result != r) { // We previously got, say, Left is better in one place. Now we have that Right // is better in one place. We know we can bail out at this point; neither is // going to be better than the other. // But first, let's see if we can ignore the ambiguity due to an undocumented legacy behavior of the compiler. // This is not part of the language spec. if (okToDowngradeResultToNeither) { if (okToDowngradeToNeither) { // Ignore the new information and the current result. Going forward, // continue ignoring any downgradable information. result = BetterResult.Neither; okToDowngradeResultToNeither = false; ignoreDowngradableToNeither = true; continue; } else { // Current result can be ignored, but the new information cannot be ignored. // Let's ignore the current result. result = r; okToDowngradeResultToNeither = false; continue; } } else if (okToDowngradeToNeither) { // Current result cannot be ignored, but the new information can be ignored. // Let's ignore it and continue with the current result. continue; } result = BetterResult.Neither; break; } else { Debug.Assert(result == r); Debug.Assert(result == BetterResult.Left || result == BetterResult.Right); okToDowngradeResultToNeither = (okToDowngradeResultToNeither && okToDowngradeToNeither); } } // Was one unambiguously better? Return it. if (result != BetterResult.Neither) { return result; } // In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are // equivalent ignoring Task-like differences (i.e. each Pi has an identity conversion to the corresponding Qi), the // following tie-breaking rules are applied, in order, to determine the better function // member. int m1ParameterCount; int m2ParameterCount; int m1ParametersUsedIncludingExpansionAndOptional; int m2ParametersUsedIncludingExpansionAndOptional; GetParameterCounts(m1, arguments, out m1ParameterCount, out m1ParametersUsedIncludingExpansionAndOptional); GetParameterCounts(m2, arguments, out m2ParameterCount, out m2ParametersUsedIncludingExpansionAndOptional); // We might have got out of the loop above early and allSame isn't completely calculated. // We need to ensure that we are not going to skip over the next 'if' because of that. // One way we can break out of the above loop early is when the corresponding method parameters have identical types // but different ref kinds. See RefOmittedComCall_OverloadResolution_MultipleArguments_ErrorCases for an example. if (allSame && m1ParametersUsedIncludingExpansionAndOptional == m2ParametersUsedIncludingExpansionAndOptional) { // Complete comparison for the remaining parameter types for (i = i + 1; i < arguments.Count; ++i) { var argumentKind = arguments[i].Kind; // If these are both applicable varargs methods and we're looking at the __arglist argument // then clearly neither of them is going to be better in this argument. if (argumentKind == BoundKind.ArgListOperator) { Debug.Assert(i == arguments.Count - 1); Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg()); continue; } var parameter1 = GetParameter(i, m1.Result, m1LeastOverriddenParameters); var type1 = GetParameterType(parameter1, m1.Result); var parameter2 = GetParameter(i, m2.Result, m2LeastOverriddenParameters); var type2 = GetParameterType(parameter2, m2.Result); var type1Normalized = type1; var type2Normalized = type2; if (!_binder.InAttributeArgument) { type1Normalized = type1.NormalizeTaskTypes(Compilation); type2Normalized = type2.NormalizeTaskTypes(Compilation); } if (Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, ref useSiteInfo).Kind != ConversionKind.Identity) { allSame = false; break; } } } // SPEC VIOLATION: When checking for matching parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN}, // native compiler includes types of optional parameters. We partially duplicate this behavior // here by comparing the number of parameters used taking params expansion and // optional parameters into account. if (!allSame || m1ParametersUsedIncludingExpansionAndOptional != m2ParametersUsedIncludingExpansionAndOptional) { // SPEC VIOLATION: Even when parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are // not equivalent, we have tie-breaking rules. // // Relevant code in the native compiler is at the end of // BetterTypeEnum ExpressionBinder::WhichMethodIsBetter( // const CandidateFunctionMember &node1, // const CandidateFunctionMember &node2, // Type* pTypeThrough, // ArgInfos*args) // if (m1ParametersUsedIncludingExpansionAndOptional != m2ParametersUsedIncludingExpansionAndOptional) { if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { if (m2.Result.Kind != MemberResolutionKind.ApplicableInExpandedForm) { return BetterResult.Right; } } else if (m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { Debug.Assert(m1.Result.Kind != MemberResolutionKind.ApplicableInExpandedForm); return BetterResult.Left; } // Here, if both methods needed to use optionals to fill in the signatures, // then we are ambiguous. Otherwise, take the one that didn't need any // optionals. if (m1ParametersUsedIncludingExpansionAndOptional == arguments.Count) { return BetterResult.Left; } else if (m2ParametersUsedIncludingExpansionAndOptional == arguments.Count) { return BetterResult.Right; } } return PreferValOverInOrRefInterpolatedHandlerParameters(arguments, m1, m1LeastOverriddenParameters, m2, m2LeastOverriddenParameters); } // If MP is a non-generic method and MQ is a generic method, then MP is better than MQ. if (m1.Member.GetMemberArity() == 0) { if (m2.Member.GetMemberArity() > 0) { return BetterResult.Left; } } else if (m2.Member.GetMemberArity() == 0) { return BetterResult.Right; } // Otherwise, if MP is applicable in its normal form and MQ has a params array and is // applicable only in its expanded form, then MP is better than MQ. if (m1.Result.Kind == MemberResolutionKind.ApplicableInNormalForm && m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { return BetterResult.Left; } if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm && m2.Result.Kind == MemberResolutionKind.ApplicableInNormalForm) { return BetterResult.Right; } // SPEC ERROR: The spec has a minor error in working here. It says: // // Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ. // This can occur if both methods have params arrays and are applicable only in their // expanded forms. // // The explanatory text actually should be normative. It should say: // // Otherwise, if both methods have params arrays and are applicable only in their // expanded forms, and if MP has more declared parameters than MQ, then MP is better than MQ. if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm && m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { if (m1ParameterCount > m2ParameterCount) { return BetterResult.Left; } if (m1ParameterCount < m2ParameterCount) { return BetterResult.Right; } } // Otherwise if all parameters of MP have a corresponding argument whereas default // arguments need to be substituted for at least one optional parameter in MQ then MP is // better than MQ. bool hasAll1 = m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm || m1ParameterCount == arguments.Count; bool hasAll2 = m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm || m2ParameterCount == arguments.Count; if (hasAll1 && !hasAll2) { return BetterResult.Left; } if (!hasAll1 && hasAll2) { return BetterResult.Right; } // Otherwise, if MP has more specific parameter types than MQ, then MP is better than // MQ. Let {R1, R2, …, RN} and {S1, S2, …, SN} represent the uninstantiated and // unexpanded parameter types of MP and MQ. MP's parameter types are more specific than // MQ's if, for each parameter, RX is not less specific than SX, and, for at least one // parameter, RX is more specific than SX // NB: OriginalDefinition, not ConstructedFrom. Substitutions into containing symbols // must also be ignored for this tie-breaker. var uninst1 = ArrayBuilder<TypeSymbol>.GetInstance(); var uninst2 = ArrayBuilder<TypeSymbol>.GetInstance(); var m1Original = m1.LeastOverriddenMember.OriginalDefinition.GetParameters(); var m2Original = m2.LeastOverriddenMember.OriginalDefinition.GetParameters(); for (i = 0; i < arguments.Count; ++i) { // If these are both applicable varargs methods and we're looking at the __arglist argument // then clearly neither of them is going to be better in this argument. if (arguments[i].Kind == BoundKind.ArgListOperator) { Debug.Assert(i == arguments.Count - 1); Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg()); continue; } var parameter1 = GetParameter(i, m1.Result, m1Original); uninst1.Add(GetParameterType(parameter1, m1.Result)); var parameter2 = GetParameter(i, m2.Result, m2Original); uninst2.Add(GetParameterType(parameter2, m2.Result)); } result = MoreSpecificType(uninst1, uninst2, ref useSiteInfo); uninst1.Free(); uninst2.Free(); if (result != BetterResult.Neither) { return result; } // UNDONE: Otherwise if one member is a non-lifted operator and the other is a lifted // operator, the non-lifted one is better. // Otherwise: Position in interactive submission chain. The last definition wins. if (m1.Member.ContainingType.TypeKind == TypeKind.Submission && m2.Member.ContainingType.TypeKind == TypeKind.Submission) { // script class is always defined in source: var compilation1 = m1.Member.DeclaringCompilation; var compilation2 = m2.Member.DeclaringCompilation; int submissionId1 = compilation1.GetSubmissionSlotIndex(); int submissionId2 = compilation2.GetSubmissionSlotIndex(); if (submissionId1 > submissionId2) { return BetterResult.Left; } if (submissionId1 < submissionId2) { return BetterResult.Right; } } // Otherwise, if one has fewer custom modifiers, that is better int m1ModifierCount = m1.LeastOverriddenMember.CustomModifierCount(); int m2ModifierCount = m2.LeastOverriddenMember.CustomModifierCount(); if (m1ModifierCount != m2ModifierCount) { return (m1ModifierCount < m2ModifierCount) ? BetterResult.Left : BetterResult.Right; } // Otherwise, prefer methods with 'val' parameters over 'in' parameters and over 'ref' parameters when the argument is an interpolated string handler. return PreferValOverInOrRefInterpolatedHandlerParameters(arguments, m1, m1LeastOverriddenParameters, m2, m2LeastOverriddenParameters); } private static BetterResult PreferValOverInOrRefInterpolatedHandlerParameters<TMember>( ArrayBuilder<BoundExpression> arguments, MemberResolutionResult<TMember> m1, ImmutableArray<ParameterSymbol> parameters1, MemberResolutionResult<TMember> m2, ImmutableArray<ParameterSymbol> parameters2) where TMember : Symbol { BetterResult valOverInOrRefInterpolatedHandlerPreference = BetterResult.Neither; for (int i = 0; i < arguments.Count; ++i) { if (arguments[i].Kind != BoundKind.ArgListOperator) { var p1 = GetParameter(i, m1.Result, parameters1); var p2 = GetParameter(i, m2.Result, parameters2); bool isInterpolatedStringHandlerConversion = false; if (m1.IsValid && m2.IsValid) { var c1 = m1.Result.ConversionForArg(i); var c2 = m2.Result.ConversionForArg(i); isInterpolatedStringHandlerConversion = c1.IsInterpolatedStringHandler && c2.IsInterpolatedStringHandler; Debug.Assert(!isInterpolatedStringHandlerConversion || arguments[i] is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }); } if (p1.RefKind == RefKind.None && isAcceptableRefMismatch(p2.RefKind, isInterpolatedStringHandlerConversion)) { if (valOverInOrRefInterpolatedHandlerPreference == BetterResult.Right) { return BetterResult.Neither; } else { valOverInOrRefInterpolatedHandlerPreference = BetterResult.Left; } } else if (p2.RefKind == RefKind.None && isAcceptableRefMismatch(p1.RefKind, isInterpolatedStringHandlerConversion)) { if (valOverInOrRefInterpolatedHandlerPreference == BetterResult.Left) { return BetterResult.Neither; } else { valOverInOrRefInterpolatedHandlerPreference = BetterResult.Right; } } } } return valOverInOrRefInterpolatedHandlerPreference; static bool isAcceptableRefMismatch(RefKind refKind, bool isInterpolatedStringHandlerConversion) => refKind switch { RefKind.In => true, RefKind.Ref when isInterpolatedStringHandlerConversion => true, _ => false }; } private static void GetParameterCounts<TMember>(MemberResolutionResult<TMember> m, ArrayBuilder<BoundExpression> arguments, out int declaredParameterCount, out int parametersUsedIncludingExpansionAndOptional) where TMember : Symbol { declaredParameterCount = m.Member.GetParameterCount(); if (m.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { if (arguments.Count < declaredParameterCount) { ImmutableArray<int> argsToParamsOpt = m.Result.ArgsToParamsOpt; if (argsToParamsOpt.IsDefaultOrEmpty || !argsToParamsOpt.Contains(declaredParameterCount - 1)) { // params parameter isn't used (see ExpressionBinder::TryGetExpandedParams in the native compiler) parametersUsedIncludingExpansionAndOptional = declaredParameterCount - 1; } else { // params parameter is used by a named argument parametersUsedIncludingExpansionAndOptional = declaredParameterCount; } } else { parametersUsedIncludingExpansionAndOptional = arguments.Count; } } else { parametersUsedIncludingExpansionAndOptional = declaredParameterCount; } } private static BetterResult MoreSpecificType(ArrayBuilder<TypeSymbol> t1, ArrayBuilder<TypeSymbol> t2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(t1.Count == t2.Count); // For t1 to be more specific than t2, it has to be not less specific in every member, // and more specific in at least one. var result = BetterResult.Neither; for (int i = 0; i < t1.Count; ++i) { var r = MoreSpecificType(t1[i], t2[i], ref useSiteInfo); if (r == BetterResult.Neither) { // We learned nothing. Do nothing. } else if (result == BetterResult.Neither) { // We have found the first more specific type. See if // all the rest on this side are not less specific. result = r; } else if (result != r) { // We have more specific types on both left and right, so we // cannot succeed in picking a better type list. Bail out now. return BetterResult.Neither; } } return result; } private static BetterResult MoreSpecificType(TypeSymbol t1, TypeSymbol t2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Spec 7.5.3.2: // - A type parameter is less specific than a non-type parameter. var t1IsTypeParameter = t1.IsTypeParameter(); var t2IsTypeParameter = t2.IsTypeParameter(); if (t1IsTypeParameter && !t2IsTypeParameter) { return BetterResult.Right; } if (!t1IsTypeParameter && t2IsTypeParameter) { return BetterResult.Left; } if (t1IsTypeParameter && t2IsTypeParameter) { return BetterResult.Neither; } // Spec: // - An array type is more specific than another array type (with the same number of dimensions) // if the element type of the first is more specific than the element type of the second. if (t1.IsArray()) { var arr1 = (ArrayTypeSymbol)t1; var arr2 = (ArrayTypeSymbol)t2; // We should not have gotten here unless there were identity conversions // between the two types. Debug.Assert(arr1.HasSameShapeAs(arr2)); return MoreSpecificType(arr1.ElementType, arr2.ElementType, ref useSiteInfo); } // SPEC EXTENSION: We apply the same rule to pointer types. if (t1.TypeKind == TypeKind.Pointer) { var p1 = (PointerTypeSymbol)t1; var p2 = (PointerTypeSymbol)t2; return MoreSpecificType(p1.PointedAtType, p2.PointedAtType, ref useSiteInfo); } if (t1.IsDynamic() || t2.IsDynamic()) { Debug.Assert(t1.IsDynamic() && t2.IsDynamic() || t1.IsDynamic() && t2.SpecialType == SpecialType.System_Object || t2.IsDynamic() && t1.SpecialType == SpecialType.System_Object); return BetterResult.Neither; } // Spec: // - A constructed type is more specific than another // constructed type (with the same number of type arguments) if at least one type // argument is more specific and no type argument is less specific than the // corresponding type argument in the other. var n1 = t1 as NamedTypeSymbol; var n2 = t2 as NamedTypeSymbol; Debug.Assert(((object)n1 == null) == ((object)n2 == null)); if ((object)n1 == null) { return BetterResult.Neither; } // We should not have gotten here unless there were identity conversions between the // two types, or they are different Task-likes. Ideally we'd assert that the two types (or // Task equivalents) have the same OriginalDefinition but we don't have a Compilation // here for NormalizeTaskTypes. var allTypeArgs1 = ArrayBuilder<TypeSymbol>.GetInstance(); var allTypeArgs2 = ArrayBuilder<TypeSymbol>.GetInstance(); n1.GetAllTypeArguments(allTypeArgs1, ref useSiteInfo); n2.GetAllTypeArguments(allTypeArgs2, ref useSiteInfo); var result = MoreSpecificType(allTypeArgs1, allTypeArgs2, ref useSiteInfo); allTypeArgs1.Free(); allTypeArgs2.Free(); return result; } // Determine whether t1 or t2 is a better conversion target from node. private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, TypeSymbol t2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { bool ignore; return BetterConversionFromExpression( node, t1, Conversions.ClassifyImplicitConversionFromExpression(node, t1, ref useSiteInfo), t2, Conversions.ClassifyImplicitConversionFromExpression(node, t2, ref useSiteInfo), ref useSiteInfo, out ignore); } // Determine whether t1 or t2 is a better conversion target from node, possibly considering parameter ref kinds. private BetterResult BetterConversionFromExpression( BoundExpression node, TypeSymbol t1, Conversion conv1, RefKind refKind1, TypeSymbol t2, Conversion conv2, RefKind refKind2, bool considerRefKinds, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool okToDowngradeToNeither) { okToDowngradeToNeither = false; if (considerRefKinds) { // We may need to consider the ref kinds of the parameters while determining the better conversion from the given expression to the respective parameter types. // This is needed for the omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method within a COM imported type. // We can reach here only if we had at least one ref omitted argument for the given call, which must be a call to a method within a COM imported type. // Algorithm for determining the better conversion from expression when ref kinds need to be considered is NOT provided in the C# language specification, // see section 7.5.3.3 'Better Conversion From Expression'. // We match native compiler's behavior for determining the better conversion as follows: // 1) If one of the contending parameters is a 'ref' parameter, say p1, and other is a non-ref parameter, say p2, // then p2 is a better result if the argument has an identity conversion to p2's type. Otherwise, neither result is better. // 2) Otherwise, if both the contending parameters are 'ref' parameters, neither result is better. // 3) Otherwise, we use the algorithm in 7.5.3.3 for determining the better conversion without considering ref kinds. // NOTE: Native compiler does not explicitly implement the above algorithm, but gets it by default. This is due to the fact that the RefKind of a parameter // NOTE: gets considered while classifying conversions between parameter types when computing better conversion target in the native compiler. // NOTE: Roslyn correctly follows the specification and ref kinds are not considered while classifying conversions between types, see method BetterConversionTarget. Debug.Assert(refKind1 == RefKind.None || refKind1 == RefKind.Ref); Debug.Assert(refKind2 == RefKind.None || refKind2 == RefKind.Ref); if (refKind1 != refKind2) { if (refKind1 == RefKind.None) { return conv1.Kind == ConversionKind.Identity ? BetterResult.Left : BetterResult.Neither; } else { return conv2.Kind == ConversionKind.Identity ? BetterResult.Right : BetterResult.Neither; } } else if (refKind1 == RefKind.Ref) { return BetterResult.Neither; } } return BetterConversionFromExpression(node, t1, conv1, t2, conv2, ref useSiteInfo, out okToDowngradeToNeither); } // Determine whether t1 or t2 is a better conversion target from node. private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, Conversion conv1, TypeSymbol t2, Conversion conv2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool okToDowngradeToNeither) { okToDowngradeToNeither = false; if (Conversions.HasIdentityConversion(t1, t2)) { // Both parameters have the same type. return BetterResult.Neither; } var lambdaOpt = node as UnboundLambda; var nodeKind = node.Kind; if (nodeKind == BoundKind.OutVariablePendingInference || nodeKind == BoundKind.OutDeconstructVarPendingInference || (nodeKind == BoundKind.DiscardExpression && !node.HasExpressionType())) { // Neither conversion from expression is better when the argument is an implicitly-typed out variable declaration. okToDowngradeToNeither = false; return BetterResult.Neither; } // C# 10 added interpolated string handler conversions, with the following rule: // Given an implicit conversion C1 that converts from an expression E to a type T1, // and an implicit conversion C2 that converts from an expression E to a type T2, // C1 is a better conversion than C2 if E is a non-constant interpolated string expression, C1 // is an interpolated string handler conversion, and C2 is not an interpolated string // handler conversion. // We deviate from our usual policy around language version not changing binding behavior here // because this will cause existing code that chooses one overload to instead choose an overload // that will immediately cause an error. True, the user does need to update their target framework // or a library to a version that takes advantage of the feature, but we made this pragmatic // choice after we received customer reports of problems in the space. // https://github.com/dotnet/roslyn/issues/55345 if (_binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && node is BoundUnconvertedInterpolatedString { ConstantValueOpt: null } or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true, ConstantValue: null }) { switch ((conv1.Kind, conv2.Kind)) { case (ConversionKind.InterpolatedStringHandler, ConversionKind.InterpolatedStringHandler): return BetterResult.Neither; case (ConversionKind.InterpolatedStringHandler, _): return BetterResult.Left; case (_, ConversionKind.InterpolatedStringHandler): return BetterResult.Right; } } // Given an implicit conversion C1 that converts from an expression E to a type T1, // and an implicit conversion C2 that converts from an expression E to a type T2, // C1 is a better conversion than C2 if E does not exactly match T2 and one of the following holds: bool t1MatchesExactly = ExpressionMatchExactly(node, t1, ref useSiteInfo); bool t2MatchesExactly = ExpressionMatchExactly(node, t2, ref useSiteInfo); if (t1MatchesExactly) { if (!t2MatchesExactly) { // - E exactly matches T1 okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Left, lambdaOpt, t1, t2, ref useSiteInfo, false); return BetterResult.Left; } } else if (t2MatchesExactly) { okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Right, lambdaOpt, t1, t2, ref useSiteInfo, false); return BetterResult.Right; } // - C1 is not a conditional expression conversion and C2 is a conditional expression conversion if (!conv1.IsConditionalExpression && conv2.IsConditionalExpression) return BetterResult.Left; if (!conv2.IsConditionalExpression && conv1.IsConditionalExpression) return BetterResult.Right; // - T1 is a better conversion target than T2 and either C1 and C2 are both conditional expression // conversions or neither is a conditional expression conversion. return BetterConversionTarget(node, t1, conv1, t2, conv2, ref useSiteInfo, out okToDowngradeToNeither); } private bool ExpressionMatchExactly(BoundExpression node, TypeSymbol t, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Given an expression E and a type T, E exactly matches T if one of the following holds: // - E has a type S, and an identity conversion exists from S to T if ((object)node.Type != null && Conversions.HasIdentityConversion(node.Type, t)) { return true; } if (node.Kind == BoundKind.TupleLiteral) { // Recurse into tuple constituent arguments. // Even if the tuple literal has a natural type and conversion // from that type is not identity, we still have to do this // because we might be converting to a tuple type backed by // different definition of ValueTuple type. return ExpressionMatchExactly((BoundTupleLiteral)node, t, ref useSiteInfo); } // - E is an anonymous function, T is either a delegate type D or an expression tree // type Expression<D>, D has a return type Y, and one of the following holds: NamedTypeSymbol d; MethodSymbol invoke; TypeSymbol y; if (node.Kind == BoundKind.UnboundLambda && (object)(d = t.GetDelegateType()) != null && (object)(invoke = d.DelegateInvokeMethod) != null && !(y = invoke.ReturnType).IsVoidType()) { BoundLambda lambda = ((UnboundLambda)node).BindForReturnTypeInference(d); // - an inferred return type X exists for E in the context of the parameter list of D(§7.5.2.12), and an identity conversion exists from X to Y var x = lambda.GetInferredReturnType(ref useSiteInfo); if (x.HasType && Conversions.HasIdentityConversion(x.Type, y)) { return true; } if (lambda.Symbol.IsAsync) { // Dig through Task<...> for an async lambda. if (y.OriginalDefinition.IsGenericTaskType(Compilation)) { y = ((NamedTypeSymbol)y).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; } else { y = null; } } if ((object)y != null) { // - The body of E is an expression that exactly matches Y, or // has a return statement with expression and all return statements have expression that // exactly matches Y. // Handle trivial cases first switch (lambda.Body.Statements.Length) { case 0: break; case 1: if (lambda.Body.Statements[0].Kind == BoundKind.ReturnStatement) { var returnStmt = (BoundReturnStatement)lambda.Body.Statements[0]; if (returnStmt.ExpressionOpt != null && ExpressionMatchExactly(returnStmt.ExpressionOpt, y, ref useSiteInfo)) { return true; } } else { goto default; } break; default: var returnStatements = ArrayBuilder<BoundReturnStatement>.GetInstance(); var walker = new ReturnStatements(returnStatements); walker.Visit(lambda.Body); bool result = false; foreach (BoundReturnStatement r in returnStatements) { if (r.ExpressionOpt == null || !ExpressionMatchExactly(r.ExpressionOpt, y, ref useSiteInfo)) { result = false; break; } else { result = true; } } returnStatements.Free(); if (result) { return true; } break; } } } return false; } // check every argument of a tuple vs corresponding type in destination tuple type private bool ExpressionMatchExactly(BoundTupleLiteral tupleSource, TypeSymbol targetType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (targetType.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types and either is a named type return false; } var destination = (NamedTypeSymbol)targetType; var sourceArguments = tupleSource.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { if (!ExpressionMatchExactly(sourceArguments[i], destTypes[i].Type, ref useSiteInfo)) { return false; } } return true; } private class ReturnStatements : BoundTreeWalker { private readonly ArrayBuilder<BoundReturnStatement> _returns; public ReturnStatements(ArrayBuilder<BoundReturnStatement> returns) { _returns = returns; } public override BoundNode Visit(BoundNode node) { if (!(node is BoundExpression)) { return base.Visit(node); } return null; } protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { // Do not recurse into nested local functions; we don't want their returns. return null; } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { _returns.Add(node); return null; } } private const int BetterConversionTargetRecursionLimit = 100; private BetterResult BetterConversionTarget( TypeSymbol type1, TypeSymbol type2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { bool okToDowngradeToNeither; return BetterConversionTargetCore(null, type1, default(Conversion), type2, default(Conversion), ref useSiteInfo, out okToDowngradeToNeither, BetterConversionTargetRecursionLimit); } private BetterResult BetterConversionTargetCore( TypeSymbol type1, TypeSymbol type2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, int betterConversionTargetRecursionLimit) { if (betterConversionTargetRecursionLimit < 0) { return BetterResult.Neither; } bool okToDowngradeToNeither; return BetterConversionTargetCore(null, type1, default(Conversion), type2, default(Conversion), ref useSiteInfo, out okToDowngradeToNeither, betterConversionTargetRecursionLimit - 1); } private BetterResult BetterConversionTarget( BoundExpression node, TypeSymbol type1, Conversion conv1, TypeSymbol type2, Conversion conv2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool okToDowngradeToNeither) { return BetterConversionTargetCore(node, type1, conv1, type2, conv2, ref useSiteInfo, out okToDowngradeToNeither, BetterConversionTargetRecursionLimit); } private BetterResult BetterConversionTargetCore( BoundExpression node, TypeSymbol type1, Conversion conv1, TypeSymbol type2, Conversion conv2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool okToDowngradeToNeither, int betterConversionTargetRecursionLimit) { okToDowngradeToNeither = false; if (Conversions.HasIdentityConversion(type1, type2)) { // Both types are the same type. return BetterResult.Neither; } // Given two different types T1 and T2, T1 is a better conversion target than T2 if no implicit conversion from T2 to T1 exists, // and at least one of the following holds: bool type1ToType2 = Conversions.ClassifyImplicitConversionFromType(type1, type2, ref useSiteInfo).IsImplicit; bool type2ToType1 = Conversions.ClassifyImplicitConversionFromType(type2, type1, ref useSiteInfo).IsImplicit; UnboundLambda lambdaOpt = node as UnboundLambda; if (type1ToType2) { if (type2ToType1) { // An implicit conversion both ways. return BetterResult.Neither; } // - An implicit conversion from T1 to T2 exists okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Left, lambdaOpt, type1, type2, ref useSiteInfo, true); return BetterResult.Left; } else if (type2ToType1) { // - An implicit conversion from T1 to T2 exists okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Right, lambdaOpt, type1, type2, ref useSiteInfo, true); return BetterResult.Right; } bool type1IsGenericTask = type1.OriginalDefinition.IsGenericTaskType(Compilation); bool type2IsGenericTask = type2.OriginalDefinition.IsGenericTaskType(Compilation); if (type1IsGenericTask) { if (type2IsGenericTask) { // - T1 is Task<S1>, T2 is Task<S2>, and S1 is a better conversion target than S2 return BetterConversionTargetCore(((NamedTypeSymbol)type1).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ((NamedTypeSymbol)type2).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, betterConversionTargetRecursionLimit); } // A shortcut, Task<T> type cannot satisfy other rules. return BetterResult.Neither; } else if (type2IsGenericTask) { // A shortcut, Task<T> type cannot satisfy other rules. return BetterResult.Neither; } NamedTypeSymbol d1; if ((object)(d1 = type1.GetDelegateType()) != null) { NamedTypeSymbol d2; if ((object)(d2 = type2.GetDelegateType()) != null) { // - T1 is either a delegate type D1 or an expression tree type Expression<D1>, // T2 is either a delegate type D2 or an expression tree type Expression<D2>, // D1 has a return type S1 and one of the following holds: MethodSymbol invoke1 = d1.DelegateInvokeMethod; MethodSymbol invoke2 = d2.DelegateInvokeMethod; if ((object)invoke1 != null && (object)invoke2 != null) { TypeSymbol r1 = invoke1.ReturnType; TypeSymbol r2 = invoke2.ReturnType; BetterResult delegateResult = BetterResult.Neither; if (!r1.IsVoidType()) { if (r2.IsVoidType()) { // - D2 is void returning delegateResult = BetterResult.Left; } } else if (!r2.IsVoidType()) { // - D2 is void returning delegateResult = BetterResult.Right; } if (delegateResult == BetterResult.Neither) { // - D2 has a return type S2, and S1 is a better conversion target than S2 delegateResult = BetterConversionTargetCore(r1, r2, ref useSiteInfo, betterConversionTargetRecursionLimit); } // Downgrade result to Neither if conversion used by the winner isn't actually valid method group conversion. // This is necessary to preserve compatibility, otherwise we might dismiss "worse", but truly applicable candidate // based on a "better", but, in reality, erroneous one. if (node?.Kind == BoundKind.MethodGroup) { var group = (BoundMethodGroup)node; if (delegateResult == BetterResult.Left) { if (IsMethodGroupConversionIncompatibleWithDelegate(group, d1, conv1)) { return BetterResult.Neither; } } else if (delegateResult == BetterResult.Right && IsMethodGroupConversionIncompatibleWithDelegate(group, d2, conv2)) { return BetterResult.Neither; } } return delegateResult; } } // A shortcut, a delegate or an expression tree cannot satisfy other rules. return BetterResult.Neither; } else if ((object)type2.GetDelegateType() != null) { // A shortcut, a delegate or an expression tree cannot satisfy other rules. return BetterResult.Neither; } // -T1 is a signed integral type and T2 is an unsigned integral type.Specifically: // - T1 is sbyte and T2 is byte, ushort, uint, or ulong // - T1 is short and T2 is ushort, uint, or ulong // - T1 is int and T2 is uint, or ulong // - T1 is long and T2 is ulong if (IsSignedIntegralType(type1)) { if (IsUnsignedIntegralType(type2)) { return BetterResult.Left; } } else if (IsUnsignedIntegralType(type1) && IsSignedIntegralType(type2)) { return BetterResult.Right; } return BetterResult.Neither; } private bool IsMethodGroupConversionIncompatibleWithDelegate(BoundMethodGroup node, NamedTypeSymbol delegateType, Conversion conv) { if (conv.IsMethodGroup) { bool result = !_binder.MethodIsCompatibleWithDelegateOrFunctionPointer(node.ReceiverOpt, conv.IsExtensionMethod, conv.Method, delegateType, Location.None, BindingDiagnosticBag.Discarded); return result; } return false; } private bool CanDowngradeConversionFromLambdaToNeither(BetterResult currentResult, UnboundLambda lambda, TypeSymbol type1, TypeSymbol type2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool fromTypeAnalysis) { // DELIBERATE SPEC VIOLATION: See bug 11961. // The native compiler uses one algorithm for determining betterness of lambdas and another one // for everything else. This is wrong; the correct behavior is to do the type analysis of // the parameter types first, and then if necessary, do the lambda analysis. Native compiler // skips analysis of the parameter types when they are delegate types with identical parameter // lists and the corresponding argument is a lambda. // There is a real-world code that breaks if we follow the specification, so we will try to fall // back to the original behavior to avoid an ambiguity that wasn't an ambiguity before. NamedTypeSymbol d1; if ((object)(d1 = type1.GetDelegateType()) != null) { NamedTypeSymbol d2; if ((object)(d2 = type2.GetDelegateType()) != null) { MethodSymbol invoke1 = d1.DelegateInvokeMethod; MethodSymbol invoke2 = d2.DelegateInvokeMethod; if ((object)invoke1 != null && (object)invoke2 != null) { if (!IdenticalParameters(invoke1.Parameters, invoke2.Parameters)) { return true; } TypeSymbol r1 = invoke1.ReturnType; TypeSymbol r2 = invoke2.ReturnType; #if DEBUG if (fromTypeAnalysis) { Debug.Assert((r1.IsVoidType()) == (r2.IsVoidType())); // Since we are dealing with variance delegate conversion and delegates have identical parameter // lists, return types must be different and neither can be void. Debug.Assert(!r1.IsVoidType()); Debug.Assert(!r2.IsVoidType()); Debug.Assert(!Conversions.HasIdentityConversion(r1, r2)); } #endif if (r1.IsVoidType()) { if (r2.IsVoidType()) { return true; } Debug.Assert(currentResult == BetterResult.Right); return false; } else if (r2.IsVoidType()) { Debug.Assert(currentResult == BetterResult.Left); return false; } if (Conversions.HasIdentityConversion(r1, r2)) { return true; } var x = lambda.InferReturnType(Conversions, d1, ref useSiteInfo); if (!x.HasType) { return true; } #if DEBUG if (fromTypeAnalysis) { // Since we are dealing with variance delegate conversion and delegates have identical parameter // lists, return types must be implicitly convertible in the same direction. // Or we might be dealing with error return types and we may have one error delegate matching exactly // while another not being an error and not convertible. Debug.Assert( r1.IsErrorType() || r2.IsErrorType() || currentResult == BetterConversionTarget(r1, r2, ref useSiteInfo)); } #endif } } } return false; } private static bool IdenticalParameters(ImmutableArray<ParameterSymbol> p1, ImmutableArray<ParameterSymbol> p2) { if (p1.IsDefault || p2.IsDefault) { // This only happens in error scenarios. return false; } if (p1.Length != p2.Length) { return false; } for (int i = 0; i < p1.Length; ++i) { var param1 = p1[i]; var param2 = p2[i]; if (param1.RefKind != param2.RefKind) { return false; } if (!Conversions.HasIdentityConversion(param1.Type, param2.Type)) { return false; } } return true; } private static bool IsSignedIntegralType(TypeSymbol type) { if ((object)type != null && type.IsNullableType()) { type = type.GetNullableUnderlyingType(); } switch (type.GetSpecialTypeSafe()) { case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_IntPtr: return true; default: return false; } } private static bool IsUnsignedIntegralType(TypeSymbol type) { if ((object)type != null && type.IsNullableType()) { type = type.GetNullableUnderlyingType(); } switch (type.GetSpecialTypeSafe()) { case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_UIntPtr: return true; default: return false; } } internal static void GetEffectiveParameterTypes( MethodSymbol method, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, bool expanded, out ImmutableArray<TypeWithAnnotations> parameterTypes, out ImmutableArray<RefKind> parameterRefKinds) { bool hasAnyRefOmittedArgument; EffectiveParameters effectiveParameters = expanded ? GetEffectiveParametersInExpandedForm(method, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, binder, out hasAnyRefOmittedArgument) : GetEffectiveParametersInNormalForm(method, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, binder, out hasAnyRefOmittedArgument); parameterTypes = effectiveParameters.ParameterTypes; parameterRefKinds = effectiveParameters.ParameterRefKinds; } private struct EffectiveParameters { internal readonly ImmutableArray<TypeWithAnnotations> ParameterTypes; internal readonly ImmutableArray<RefKind> ParameterRefKinds; internal EffectiveParameters(ImmutableArray<TypeWithAnnotations> types, ImmutableArray<RefKind> refKinds) { ParameterTypes = types; ParameterRefKinds = refKinds; } } private EffectiveParameters GetEffectiveParametersInNormalForm<TMember>( TMember member, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments) where TMember : Symbol { bool discarded; return GetEffectiveParametersInNormalForm(member, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, hasAnyRefOmittedArgument: out discarded); } private static EffectiveParameters GetEffectiveParametersInNormalForm<TMember>( TMember member, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, out bool hasAnyRefOmittedArgument) where TMember : Symbol { Debug.Assert(argumentRefKinds != null); hasAnyRefOmittedArgument = false; ImmutableArray<ParameterSymbol> parameters = member.GetParameters(); // We simulate an extra parameter for vararg methods int parameterCount = member.GetParameterCount() + (member.GetIsVararg() ? 1 : 0); if (argumentCount == parameterCount && argToParamMap.IsDefaultOrEmpty) { ImmutableArray<RefKind> parameterRefKinds = member.GetParameterRefKinds(); if (parameterRefKinds.IsDefaultOrEmpty) { return new EffectiveParameters(member.GetParameterTypes(), parameterRefKinds); } } var types = ArrayBuilder<TypeWithAnnotations>.GetInstance(); ArrayBuilder<RefKind> refs = null; bool hasAnyRefArg = argumentRefKinds.Any(); for (int arg = 0; arg < argumentCount; ++arg) { int parm = argToParamMap.IsDefault ? arg : argToParamMap[arg]; // If this is the __arglist parameter, or an extra argument in error situations, just skip it. if (parm >= parameters.Length) { continue; } var parameter = parameters[parm]; types.Add(parameter.TypeWithAnnotations); RefKind argRefKind = hasAnyRefArg ? argumentRefKinds[arg] : RefKind.None; RefKind paramRefKind = GetEffectiveParameterRefKind(parameter, argRefKind, isMethodGroupConversion, allowRefOmittedArguments, binder, ref hasAnyRefOmittedArgument); if (refs == null) { if (paramRefKind != RefKind.None) { refs = ArrayBuilder<RefKind>.GetInstance(arg, RefKind.None); refs.Add(paramRefKind); } } else { refs.Add(paramRefKind); } } var refKinds = refs != null ? refs.ToImmutableAndFree() : default(ImmutableArray<RefKind>); return new EffectiveParameters(types.ToImmutableAndFree(), refKinds); } private static RefKind GetEffectiveParameterRefKind( ParameterSymbol parameter, RefKind argRefKind, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, ref bool hasAnyRefOmittedArgument) { var paramRefKind = parameter.RefKind; // 'None' argument is allowed to match 'In' parameter and should behave like 'None' for the purpose of overload resolution // unless this is a method group conversion where 'In' must match 'In' if (!isMethodGroupConversion && argRefKind == RefKind.None && paramRefKind == RefKind.In) { return RefKind.None; } // Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method/property on an instance of a COM imported type. // We must ignore the 'ref' on the parameter while determining the applicability of argument for the given method call. // During argument rewriting, we will replace the argument value with a temporary local and pass that local by reference. if (allowRefOmittedArguments && paramRefKind == RefKind.Ref && argRefKind == RefKind.None && !binder.InAttributeArgument) { hasAnyRefOmittedArgument = true; return RefKind.None; } return paramRefKind; } private EffectiveParameters GetEffectiveParametersInExpandedForm<TMember>( TMember member, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments) where TMember : Symbol { bool discarded; return GetEffectiveParametersInExpandedForm(member, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, hasAnyRefOmittedArgument: out discarded); } private static EffectiveParameters GetEffectiveParametersInExpandedForm<TMember>( TMember member, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, out bool hasAnyRefOmittedArgument) where TMember : Symbol { Debug.Assert(argumentRefKinds != null); var types = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var refs = ArrayBuilder<RefKind>.GetInstance(); bool anyRef = false; var parameters = member.GetParameters(); bool hasAnyRefArg = argumentRefKinds.Any(); hasAnyRefOmittedArgument = false; for (int arg = 0; arg < argumentCount; ++arg) { var parm = argToParamMap.IsDefault ? arg : argToParamMap[arg]; var parameter = parameters[parm]; var type = parameter.TypeWithAnnotations; types.Add(parm == parameters.Length - 1 ? ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations : type); var argRefKind = hasAnyRefArg ? argumentRefKinds[arg] : RefKind.None; var paramRefKind = GetEffectiveParameterRefKind(parameter, argRefKind, isMethodGroupConversion, allowRefOmittedArguments, binder, ref hasAnyRefOmittedArgument); refs.Add(paramRefKind); if (paramRefKind != RefKind.None) { anyRef = true; } } var refKinds = anyRef ? refs.ToImmutable() : default(ImmutableArray<RefKind>); refs.Free(); return new EffectiveParameters(types.ToImmutableAndFree(), refKinds); } private MemberResolutionResult<TMember> IsMemberApplicableInNormalForm<TMember>( TMember member, // method or property TMember leastOverriddenMember, // method or property ArrayBuilder<TypeWithAnnotations> typeArguments, AnalyzedArguments arguments, bool isMethodGroupConversion, bool allowRefOmittedArguments, bool inferWithDynamic, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { // AnalyzeArguments matches arguments to parameter names and positions. // For that purpose we use the most derived member. var argumentAnalysis = AnalyzeArguments(member, arguments, isMethodGroupConversion, expanded: false); if (!argumentAnalysis.IsValid) { switch (argumentAnalysis.Kind) { case ArgumentAnalysisResultKind.RequiredParameterMissing: case ArgumentAnalysisResultKind.NoCorrespondingParameter: case ArgumentAnalysisResultKind.DuplicateNamedArgument: if (!completeResults) goto default; // When we are producing more complete results, and we have the wrong number of arguments, we push on // through type inference so that lambda arguments can be bound to their delegate-typed parameters, // thus improving the API and intellisense experience. break; default: return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis)); } } // Check after argument analysis, but before more complicated type inference and argument type validation. // NOTE: The diagnostic may not be reported (e.g. if the member is later removed as less-derived). if (member.HasUseSiteError) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UseSiteError()); } bool hasAnyRefOmittedArgument; // To determine parameter types we use the originalMember. EffectiveParameters originalEffectiveParameters = GetEffectiveParametersInNormalForm( GetConstructedFrom(leastOverriddenMember), arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, out hasAnyRefOmittedArgument); Debug.Assert(!hasAnyRefOmittedArgument || allowRefOmittedArguments); // To determine parameter types we use the originalMember. EffectiveParameters constructedEffectiveParameters = GetEffectiveParametersInNormalForm( leastOverriddenMember, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion, allowRefOmittedArguments); // The member passed to the following call is returned in the result (possibly a constructed version of it). // The applicability is checked based on effective parameters passed in. var applicableResult = IsApplicable( member, leastOverriddenMember, typeArguments, arguments, originalEffectiveParameters, constructedEffectiveParameters, argumentAnalysis.ArgsToParamsOpt, hasAnyRefOmittedArgument: hasAnyRefOmittedArgument, inferWithDynamic: inferWithDynamic, completeResults: completeResults, useSiteInfo: ref useSiteInfo); // If we were producing complete results and had missing arguments, we pushed on in order to call IsApplicable for // type inference and lambda binding. In that case we still need to return the argument mismatch failure here. if (completeResults && !argumentAnalysis.IsValid) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis)); } return applicableResult; } private MemberResolutionResult<TMember> IsMemberApplicableInExpandedForm<TMember>( TMember member, // method or property TMember leastOverriddenMember, // method or property ArrayBuilder<TypeWithAnnotations> typeArguments, AnalyzedArguments arguments, bool allowRefOmittedArguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { // AnalyzeArguments matches arguments to parameter names and positions. // For that purpose we use the most derived member. var argumentAnalysis = AnalyzeArguments(member, arguments, isMethodGroupConversion: false, expanded: true); if (!argumentAnalysis.IsValid) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis)); } // Check after argument analysis, but before more complicated type inference and argument type validation. // NOTE: The diagnostic may not be reported (e.g. if the member is later removed as less-derived). if (member.HasUseSiteError) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UseSiteError()); } bool hasAnyRefOmittedArgument; // To determine parameter types we use the least derived member. EffectiveParameters originalEffectiveParameters = GetEffectiveParametersInExpandedForm( GetConstructedFrom(leastOverriddenMember), arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments, _binder, out hasAnyRefOmittedArgument); Debug.Assert(!hasAnyRefOmittedArgument || allowRefOmittedArguments); // To determine parameter types we use the least derived member. EffectiveParameters constructedEffectiveParameters = GetEffectiveParametersInExpandedForm( leastOverriddenMember, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments); // The member passed to the following call is returned in the result (possibly a constructed version of it). // The applicability is checked based on effective parameters passed in. var result = IsApplicable( member, leastOverriddenMember, typeArguments, arguments, originalEffectiveParameters, constructedEffectiveParameters, argumentAnalysis.ArgsToParamsOpt, hasAnyRefOmittedArgument: hasAnyRefOmittedArgument, inferWithDynamic: false, completeResults: completeResults, useSiteInfo: ref useSiteInfo); return result.Result.IsValid ? new MemberResolutionResult<TMember>( result.Member, result.LeastOverriddenMember, MemberAnalysisResult.ExpandedForm(result.Result.ArgsToParamsOpt, result.Result.ConversionsOpt, hasAnyRefOmittedArgument)) : result; } private MemberResolutionResult<TMember> IsApplicable<TMember>( TMember member, // method or property TMember leastOverriddenMember, // method or property ArrayBuilder<TypeWithAnnotations> typeArgumentsBuilder, AnalyzedArguments arguments, EffectiveParameters originalEffectiveParameters, EffectiveParameters constructedEffectiveParameters, ImmutableArray<int> argsToParamsMap, bool hasAnyRefOmittedArgument, bool inferWithDynamic, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { bool ignoreOpenTypes; MethodSymbol method; EffectiveParameters effectiveParameters; if (member.Kind == SymbolKind.Method && (method = (MethodSymbol)(Symbol)member).Arity > 0) { if (typeArgumentsBuilder.Count == 0 && arguments.HasDynamicArgument && !inferWithDynamic) { // Spec 7.5.4: Compile-time checking of dynamic overload resolution: // * First, if F is a generic method and type arguments were provided, // then those are substituted for the type parameters in the parameter list. // However, if type arguments were not provided, no such substitution happens. // * Then, any parameter whose type contains a an unsubstituted type parameter of F // is elided, along with the corresponding arguments(s). // We don't need to check constraints of types of the non-elided parameters since they // have no effect on applicability of this candidate. ignoreOpenTypes = true; effectiveParameters = constructedEffectiveParameters; } else { MethodSymbol leastOverriddenMethod = (MethodSymbol)(Symbol)leastOverriddenMember; ImmutableArray<TypeWithAnnotations> typeArguments; if (typeArgumentsBuilder.Count > 0) { // generic type arguments explicitly specified at call-site: typeArguments = typeArgumentsBuilder.ToImmutable(); } else { // infer generic type arguments: MemberAnalysisResult inferenceError; typeArguments = InferMethodTypeArguments(method, leastOverriddenMethod.ConstructedFrom.TypeParameters, arguments, originalEffectiveParameters, out inferenceError, ref useSiteInfo); if (typeArguments.IsDefault) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, inferenceError); } } member = (TMember)(Symbol)method.Construct(typeArguments); leastOverriddenMember = (TMember)(Symbol)leastOverriddenMethod.ConstructedFrom.Construct(typeArguments); // Spec (§7.6.5.1) // Once the (inferred) type arguments are substituted for the corresponding method type parameters, // all constructed types in the parameter list of F satisfy *their* constraints (§4.4.4), // and the parameter list of F is applicable with respect to A (§7.5.3.1). // // This rule is a bit complicated; let's take a look at an example. Suppose we have // class X<U> where U : struct {} // ... // void M<T>(T t, X<T> xt) where T : struct {} // void M(object o1, object o2) {} // // Suppose there is a call M("", null). Type inference infers that T is string. // M<string> is then not an applicable candidate *NOT* because string violates the // constraint on T. That is not checked until "final validation" (although when // feature 'ImprovedOverloadCandidates' is enabled in later language versions // it is checked on the candidate before overload resolution). Rather, the // method is not a candidate because string violates the constraint *on U*. // The constructed method has formal parameter type X<string>, which is not legal. // In the case given, the generic method is eliminated and the object version wins. // // Note also that the constraints need to be checked on *all* the formal parameter // types, not just the ones in the *effective parameter list*. If we had: // void M<T>(T t, X<T> xt = null) where T : struct {} // void M<T>(object o1, object o2 = null) where T : struct {} // and a call M("") then type inference still works out that T is string, and // the generic method still needs to be discarded, even though type inference // never saw the second formal parameter. var parameterTypes = leastOverriddenMember.GetParameterTypes(); for (int i = 0; i < parameterTypes.Length; i++) { if (!parameterTypes[i].Type.CheckAllConstraints(Compilation, Conversions)) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ConstructedParameterFailedConstraintsCheck(i)); } } // Types of constructed effective parameters might originate from a virtual/abstract method // that the current "method" overrides. If the virtual/abstract method is generic we constructed it // using the generic parameters of "method", so we can now substitute these type parameters // in the constructed effective parameters. var map = new TypeMap(method.TypeParameters, typeArguments, allowAlpha: true); effectiveParameters = new EffectiveParameters( map.SubstituteTypes(constructedEffectiveParameters.ParameterTypes), constructedEffectiveParameters.ParameterRefKinds); ignoreOpenTypes = false; } } else { effectiveParameters = constructedEffectiveParameters; ignoreOpenTypes = false; } var applicableResult = IsApplicable( member, effectiveParameters, arguments, argsToParamsMap, isVararg: member.GetIsVararg(), hasAnyRefOmittedArgument: hasAnyRefOmittedArgument, ignoreOpenTypes: ignoreOpenTypes, completeResults: completeResults, useSiteInfo: ref useSiteInfo); return new MemberResolutionResult<TMember>(member, leastOverriddenMember, applicableResult); } private ImmutableArray<TypeWithAnnotations> InferMethodTypeArguments( MethodSymbol method, ImmutableArray<TypeParameterSymbol> originalTypeParameters, AnalyzedArguments arguments, EffectiveParameters originalEffectiveParameters, out MemberAnalysisResult error, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var args = arguments.Arguments.ToImmutable(); // The reason why we pass the type parameters and formal parameter types // from the original definition, not the method as it exists as a member of // a possibly constructed generic type, is exceedingly subtle. See the comments // in "Infer" for details. var inferenceResult = MethodTypeInferrer.Infer( _binder, _binder.Conversions, originalTypeParameters, method.ContainingType, originalEffectiveParameters.ParameterTypes, originalEffectiveParameters.ParameterRefKinds, args, ref useSiteInfo); if (inferenceResult.Success) { error = default(MemberAnalysisResult); return inferenceResult.InferredTypeArguments; } if (arguments.IsExtensionMethodInvocation) { var inferredFromFirstArgument = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument( _binder.Compilation, _binder.Conversions, method, args, useSiteInfo: ref useSiteInfo); if (inferredFromFirstArgument.IsDefault) { error = MemberAnalysisResult.TypeInferenceExtensionInstanceArgumentFailed(); return default(ImmutableArray<TypeWithAnnotations>); } } error = MemberAnalysisResult.TypeInferenceFailed(); return default(ImmutableArray<TypeWithAnnotations>); } private MemberAnalysisResult IsApplicable( Symbol candidate, // method or property EffectiveParameters parameters, AnalyzedArguments arguments, ImmutableArray<int> argsToParameters, bool isVararg, bool hasAnyRefOmittedArgument, bool ignoreOpenTypes, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // The effective parameters are in the right order with respect to the arguments. // // The difference between "parameters" and "original parameters" is as follows. Suppose // we have class C<V> { static void M<T, U>(T t, U u, V v) { C<T>.M(1, t, t); } } // In the call, the "original parameters" are (T, U, V). The "constructed parameters", // not passed in here, are (T, U, T) because T is substituted for V; type inference then // infers that T is int and U is T. The "parameters" are therefore (int, T, T). // // We add a "virtual parameter" for the __arglist. int paramCount = parameters.ParameterTypes.Length + (isVararg ? 1 : 0); if (arguments.Arguments.Count < paramCount) { // For improved error recovery, we perform type inference even when the argument // list is of the wrong length. The caller is expected to detect and handle that, // treating the method as inapplicable. paramCount = arguments.Arguments.Count; } // For each argument in A, the parameter passing mode of the argument (i.e., value, ref, or out) is // identical to the parameter passing mode of the corresponding parameter, and // * for a value parameter or a parameter array, an implicit conversion exists from the // argument to the type of the corresponding parameter, or // * for a ref or out parameter, the type of the argument is identical to the type of the corresponding // parameter. After all, a ref or out parameter is an alias for the argument passed. ArrayBuilder<Conversion> conversions = null; ArrayBuilder<int> badArguments = null; for (int argumentPosition = 0; argumentPosition < paramCount; argumentPosition++) { BoundExpression argument = arguments.Argument(argumentPosition); Conversion conversion; if (isVararg && argumentPosition == paramCount - 1) { // Only an __arglist() expression is convertible. if (argument.Kind == BoundKind.ArgListOperator) { conversion = Conversion.Identity; } else { badArguments = badArguments ?? ArrayBuilder<int>.GetInstance(); badArguments.Add(argumentPosition); conversion = Conversion.NoConversion; } } else { RefKind argumentRefKind = arguments.RefKind(argumentPosition); RefKind parameterRefKind = parameters.ParameterRefKinds.IsDefault ? RefKind.None : parameters.ParameterRefKinds[argumentPosition]; bool forExtensionMethodThisArg = arguments.IsExtensionMethodThisArgument(argumentPosition); if (forExtensionMethodThisArg) { Debug.Assert(argumentRefKind == RefKind.None); if (parameterRefKind == RefKind.Ref) { // For ref extension methods, we omit the "ref" modifier on the receiver arguments // Passing the parameter RefKind for finding the correct conversion. // For ref-readonly extension methods, argumentRefKind is always None. argumentRefKind = parameterRefKind; } } bool hasInterpolatedStringRefMismatch = false; if (argument is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true } && parameterRefKind == RefKind.Ref && parameters.ParameterTypes[argumentPosition].Type is NamedTypeSymbol { IsInterpolatedStringHandlerType: true, IsValueType: true }) { // For interpolated strings handlers, we allow an interpolated string expression to be passed as if `ref` was specified // in the source when the handler type is a value type. // https://github.com/dotnet/roslyn/issues/54584 allow binary additions of interpolated strings to match as well. hasInterpolatedStringRefMismatch = true; argumentRefKind = parameterRefKind; } conversion = CheckArgumentForApplicability( candidate, argument, argumentRefKind, parameters.ParameterTypes[argumentPosition].Type, parameterRefKind, ignoreOpenTypes, ref useSiteInfo, forExtensionMethodThisArg, hasInterpolatedStringRefMismatch); if (forExtensionMethodThisArg && !Conversions.IsValidExtensionMethodThisArgConversion(conversion)) { // Return early, without checking conversions of subsequent arguments, // if the instance argument is not convertible to the 'this' parameter, // even when 'completeResults' is requested. This avoids unnecessary // lambda binding in particular, for instance, with LINQ expressions. // Note that BuildArgumentsForErrorRecovery will still bind some number // of overloads for the semantic model. Debug.Assert(badArguments == null); Debug.Assert(conversions == null); return MemberAnalysisResult.BadArgumentConversions(argsToParameters, ImmutableArray.Create(argumentPosition), ImmutableArray.Create(conversion)); } if (!conversion.Exists) { badArguments ??= ArrayBuilder<int>.GetInstance(); badArguments.Add(argumentPosition); } } if (conversions != null) { conversions.Add(conversion); } else if (!conversion.IsIdentity) { conversions = ArrayBuilder<Conversion>.GetInstance(paramCount); conversions.AddMany(Conversion.Identity, argumentPosition); conversions.Add(conversion); } if (badArguments != null && !completeResults) { break; } } MemberAnalysisResult result; var conversionsArray = conversions != null ? conversions.ToImmutableAndFree() : default(ImmutableArray<Conversion>); if (badArguments != null) { result = MemberAnalysisResult.BadArgumentConversions(argsToParameters, badArguments.ToImmutableAndFree(), conversionsArray); } else { result = MemberAnalysisResult.NormalForm(argsToParameters, conversionsArray, hasAnyRefOmittedArgument); } return result; } private Conversion CheckArgumentForApplicability( Symbol candidate, // method or property BoundExpression argument, RefKind argRefKind, TypeSymbol parameterType, RefKind parRefKind, bool ignoreOpenTypes, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forExtensionMethodThisArg, bool hasInterpolatedStringRefMismatch) { // Spec 7.5.3.1 // For each argument in A, the parameter passing mode of the argument (i.e., value, ref, or out) is identical // to the parameter passing mode of the corresponding parameter, and // - for a value parameter or a parameter array, an implicit conversion (§6.1) // exists from the argument to the type of the corresponding parameter, or // - for a ref or out parameter, the type of the argument is identical to the type of the corresponding parameter. // effective RefKind has to match unless argument expression is of the type dynamic. // This is a bug in Dev11 which we also implement. // The spec is correct, this is not an intended behavior. We don't fix the bug to avoid a breaking change. if (!(argRefKind == parRefKind || (argRefKind == RefKind.None && argument.HasDynamicType()))) { return Conversion.NoConversion; } // TODO (tomat): the spec wording isn't final yet // Spec 7.5.4: Compile-time checking of dynamic overload resolution: // - Then, any parameter whose type is open (i.e. contains a type parameter; see §4.4.2) is elided, along with its corresponding parameter(s). // and // - The modified parameter list for F is applicable to the modified argument list in terms of section §7.5.3.1 if (ignoreOpenTypes && parameterType.ContainsTypeParameter(parameterContainer: (MethodSymbol)candidate)) { // defer applicability check to runtime: return Conversion.ImplicitDynamic; } var argType = argument.Type; if (argument.Kind == BoundKind.OutVariablePendingInference || argument.Kind == BoundKind.OutDeconstructVarPendingInference || (argument.Kind == BoundKind.DiscardExpression && (object)argType == null)) { Debug.Assert(argRefKind != RefKind.None); // Any parameter type is good, we'll use it for the var local. return Conversion.Identity; } if (argRefKind == RefKind.None || hasInterpolatedStringRefMismatch) { var conversion = forExtensionMethodThisArg ? Conversions.ClassifyImplicitExtensionMethodThisArgConversion(argument, argument.Type, parameterType, ref useSiteInfo) : Conversions.ClassifyImplicitConversionFromExpression(argument, parameterType, ref useSiteInfo); Debug.Assert((!conversion.Exists) || conversion.IsImplicit, "ClassifyImplicitConversion should only return implicit conversions"); if (hasInterpolatedStringRefMismatch && !conversion.IsInterpolatedStringHandler) { // We allowed a ref mismatch under the assumption the conversion would be an interpolated string handler conversion. If it's not, then there was // actually no conversion because of the refkind mismatch. return Conversion.NoConversion; } return conversion; } if ((object)argType != null && Conversions.HasIdentityConversion(argType, parameterType)) { return Conversion.Identity; } else { return Conversion.NoConversion; } } private static TMember GetConstructedFrom<TMember>(TMember member) where TMember : Symbol { switch (member.Kind) { case SymbolKind.Property: return member; case SymbolKind.Method: return (TMember)(Symbol)(member as MethodSymbol).ConstructedFrom; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal enum BetterResult { Left, Right, Neither, Equal } internal sealed partial class OverloadResolution { private readonly Binder _binder; public OverloadResolution(Binder binder) { _binder = binder; } private CSharpCompilation Compilation { get { return _binder.Compilation; } } private Conversions Conversions { get { return _binder.Conversions; } } // lazily compute if the compiler is in "strict" mode (rather than duplicating bugs for compatibility) private bool? _strict; private bool Strict { get { if (_strict.HasValue) return _strict.Value; bool value = _binder.Compilation.FeatureStrictEnabled; _strict = value; return value; } } // UNDONE: This List<MethodResolutionResult> deal should probably be its own data structure. // We need an indexable collection of mappings from method candidates to their up-to-date // overload resolution status. It must be fast and memory efficient, but it will very often // contain just 1 candidate. private static bool AnyValidResult<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results) where TMember : Symbol { foreach (var result in results) { if (result.IsValid) { return true; } } return false; } private static bool SingleValidResult<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results) where TMember : Symbol { bool oneValid = false; foreach (var result in results) { if (result.IsValid) { if (oneValid) { return false; } oneValid = true; } } return oneValid; } // Perform overload resolution on the given method group, with the given arguments and // names. The names can be null if no names were supplied to any arguments. public void ObjectCreationOverloadResolution(ImmutableArray<MethodSymbol> constructors, AnalyzedArguments arguments, OverloadResolutionResult<MethodSymbol> result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var results = result.ResultsBuilder; // First, attempt overload resolution not getting complete results. PerformObjectCreationOverloadResolution(results, constructors, arguments, false, ref useSiteInfo); if (!OverloadResolutionResultIsValid(results, arguments.HasDynamicArgument)) { // We didn't get a single good result. Get full results of overload resolution and return those. result.Clear(); PerformObjectCreationOverloadResolution(results, constructors, arguments, true, ref useSiteInfo); } } // Perform overload resolution on the given method group, with the given arguments and // names. The names can be null if no names were supplied to any arguments. public void MethodInvocationOverloadResolution( ArrayBuilder<MethodSymbol> methods, ArrayBuilder<TypeWithAnnotations> typeArguments, BoundExpression receiver, AnalyzedArguments arguments, OverloadResolutionResult<MethodSymbol> result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool isMethodGroupConversion = false, bool allowRefOmittedArguments = false, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { MethodOrPropertyOverloadResolution( methods, typeArguments, receiver, arguments, result, isMethodGroupConversion, allowRefOmittedArguments, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, in callingConventionInfo); } // Perform overload resolution on the given property group, with the given arguments and // names. The names can be null if no names were supplied to any arguments. public void PropertyOverloadResolution( ArrayBuilder<PropertySymbol> indexers, BoundExpression receiverOpt, AnalyzedArguments arguments, OverloadResolutionResult<PropertySymbol> result, bool allowRefOmittedArguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<TypeWithAnnotations> typeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); MethodOrPropertyOverloadResolution( indexers, typeArguments, receiverOpt, arguments, result, isMethodGroupConversion: false, allowRefOmittedArguments: allowRefOmittedArguments, useSiteInfo: ref useSiteInfo, callingConventionInfo: default); typeArguments.Free(); } internal void MethodOrPropertyOverloadResolution<TMember>( ArrayBuilder<TMember> members, ArrayBuilder<TypeWithAnnotations> typeArguments, BoundExpression receiver, AnalyzedArguments arguments, OverloadResolutionResult<TMember> result, bool isMethodGroupConversion, bool allowRefOmittedArguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) where TMember : Symbol { var results = result.ResultsBuilder; // First, attempt overload resolution not getting complete results. PerformMemberOverloadResolution( results, members, typeArguments, receiver, arguments, completeResults: false, isMethodGroupConversion, returnRefKind, returnType, allowRefOmittedArguments, isFunctionPointerResolution, callingConventionInfo, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm); if (!OverloadResolutionResultIsValid(results, arguments.HasDynamicArgument)) { // We didn't get a single good result. Get full results of overload resolution and return those. result.Clear(); PerformMemberOverloadResolution( results, members, typeArguments, receiver, arguments, completeResults: true, isMethodGroupConversion, returnRefKind, returnType, allowRefOmittedArguments, isFunctionPointerResolution, callingConventionInfo, ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); } } private static bool OverloadResolutionResultIsValid<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, bool hasDynamicArgument) where TMember : Symbol { // If there were no dynamic arguments then overload resolution succeeds if there is exactly one method // that is applicable and not worse than another method. // // If there were dynamic arguments then overload resolution succeeds if there were one or more applicable // methods; which applicable method that will be invoked, if any, will be worked out at runtime. // // Note that we could in theory do a better job of detecting situations that we know will fail. We do not // treat methods that violate generic type constraints as inapplicable; rather, if such a method is chosen // as the best method we give an error during the "final validation" phase. In the dynamic argument // scenario there could be two methods, both applicable, ambiguous as to which is better, and neither // would pass final validation. In that case we could give the error at compile time, but we do not. if (hasDynamicArgument) { foreach (var curResult in results) { if (curResult.Result.IsApplicable) { return true; } } return false; } return SingleValidResult(results); } // Perform method/indexer overload resolution, storing the results into "results". If // completeResults is false, then invalid results don't have to be stored. The results will // still contain all possible successful resolution. private void PerformMemberOverloadResolution<TMember>( ArrayBuilder<MemberResolutionResult<TMember>> results, ArrayBuilder<TMember> members, ArrayBuilder<TypeWithAnnotations> typeArguments, BoundExpression receiver, AnalyzedArguments arguments, bool completeResults, bool isMethodGroupConversion, RefKind returnRefKind, TypeSymbol returnType, bool allowRefOmittedArguments, bool isFunctionPointerResolution, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true) where TMember : Symbol { // SPEC: The binding-time processing of a method invocation of the form M(A), where M is a // SPEC: method group (possibly including a type-argument-list), and A is an optional // SPEC: argument-list, consists of the following steps: // NOTE: We use a quadratic algorithm to determine which members override/hide // each other (i.e. we compare them pairwise). We could move to a linear // algorithm that builds the closure set of overridden/hidden members and then // uses that set to filter the candidate, but that would still involve realizing // a lot of PE symbols. Instead, we partition the candidates by containing type. // With this information, we can efficiently skip checks where the (potentially) // overriding or hiding member is not in a subtype of the type containing the // (potentially) overridden or hidden member. Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt = null; if (members.Count > 50) // TODO: fine-tune this value { containingTypeMapOpt = PartitionMembersByContainingType(members); } // SPEC: The set of candidate methods for the method invocation is constructed. for (int i = 0; i < members.Count; i++) { AddMemberToCandidateSet( members[i], results, members, typeArguments, receiver, arguments, completeResults, isMethodGroupConversion, allowRefOmittedArguments, containingTypeMapOpt, inferWithDynamic: inferWithDynamic, useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); } // CONSIDER: use containingTypeMapOpt for RemoveLessDerivedMembers? ClearContainingTypeMap(ref containingTypeMapOpt); // Remove methods that are inaccessible because their inferred type arguments are inaccessible. // It is not clear from the spec how or where this is supposed to occur. RemoveInaccessibleTypeArguments(results, ref useSiteInfo); // SPEC: The set of candidate methods is reduced to contain only methods from the most derived types. RemoveLessDerivedMembers(results, ref useSiteInfo); if (Compilation.LanguageVersion.AllowImprovedOverloadCandidates()) { RemoveStaticInstanceMismatches(results, arguments, receiver); RemoveConstraintViolations(results, template: new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo)); if (isMethodGroupConversion) { RemoveDelegateConversionsWithWrongReturnType(results, ref useSiteInfo, returnRefKind, returnType, isFunctionPointerResolution); } } if (isFunctionPointerResolution) { RemoveCallingConventionMismatches(results, callingConventionInfo); RemoveMethodsNotDeclaredStatic(results); } // NB: As in dev12, we do this AFTER removing less derived members. // Also note that less derived members are not actually removed - they are simply flagged. ReportUseSiteInfo(results, ref useSiteInfo); // SPEC: If the resulting set of candidate methods is empty, then further processing along the following steps are abandoned, // SPEC: and instead an attempt is made to process the invocation as an extension method invocation. If this fails, then no // SPEC: applicable methods exist, and a binding-time error occurs. if (!AnyValidResult(results)) { return; } // SPEC: The best method of the set of candidate methods is identified. If a single best method cannot be identified, // SPEC: the method invocation is ambiguous, and a binding-time error occurs. RemoveWorseMembers(results, arguments, ref useSiteInfo); // Note, the caller is responsible for "final validation", // as that is not part of overload resolution. } internal void FunctionPointerOverloadResolution( ArrayBuilder<FunctionPointerMethodSymbol> funcPtrBuilder, AnalyzedArguments analyzedArguments, OverloadResolutionResult<FunctionPointerMethodSymbol> overloadResolutionResult, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(funcPtrBuilder.Count == 1); Debug.Assert(funcPtrBuilder[0].Arity == 0); var typeArgumentsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); AddMemberToCandidateSet( funcPtrBuilder[0], overloadResolutionResult.ResultsBuilder, funcPtrBuilder, typeArgumentsBuilder, receiverOpt: null, analyzedArguments, completeResults: true, isMethodGroupConversion: false, allowRefOmittedArguments: false, containingTypeMapOpt: null, inferWithDynamic: false, ref useSiteInfo, allowUnexpandedForm: true); ReportUseSiteInfo(overloadResolutionResult.ResultsBuilder, ref useSiteInfo); } private void RemoveStaticInstanceMismatches<TMember>( ArrayBuilder<MemberResolutionResult<TMember>> results, AnalyzedArguments arguments, BoundExpression receiverOpt) where TMember : Symbol { // When the feature 'ImprovedOverloadCandidates' is enabled, we do not include instance members when the receiver // is a type, or static members when the receiver is an instance. This does not apply to extension method invocations, // because extension methods are only considered when the receiver is an instance. It also does not apply when the // receiver is a TypeOrValueExpression, which is used to handle the receiver of a Color-Color ambiguity, where either // an instance or a static member would be acceptable. if (arguments.IsExtensionMethodInvocation || Binder.IsTypeOrValueExpression(receiverOpt)) { return; } bool isImplicitReceiver = Binder.WasImplicitReceiver(receiverOpt); // isStaticContext includes both places where `this` isn't available, and places where it // cannot be used (e.g. a field initializer or a constructor-initializer) bool isStaticContext = !_binder.HasThis(!isImplicitReceiver, out bool inStaticContext) || inStaticContext; if (isImplicitReceiver && !isStaticContext) { return; } // We are in a context where only instance (or only static) methods are permitted. We reject the others. bool keepStatic = isImplicitReceiver && isStaticContext || Binder.IsMemberAccessedThroughType(receiverOpt); RemoveStaticInstanceMismatches(results, keepStatic); } private static void RemoveStaticInstanceMismatches<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, bool requireStatic) where TMember : Symbol { for (int f = 0; f < results.Count; ++f) { var result = results[f]; TMember member = result.Member; if (result.Result.IsValid && member.RequiresInstanceReceiver() == requireStatic) { results[f] = new MemberResolutionResult<TMember>(member, result.LeastOverriddenMember, MemberAnalysisResult.StaticInstanceMismatch()); } } } private static void RemoveMethodsNotDeclaredStatic<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results) where TMember : Symbol { // RemoveStaticInstanceMismatches allows methods that do not need a receiver but are not declared static, // such as a local function that is not declared static. This eliminates methods that are not actually // declared as static for (int f = 0; f < results.Count; f++) { var result = results[f]; TMember member = result.Member; if (result.Result.IsValid && !member.IsStatic) { results[f] = new MemberResolutionResult<TMember>(member, result.LeastOverriddenMember, MemberAnalysisResult.StaticInstanceMismatch()); } } } private void RemoveConstraintViolations<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, CompoundUseSiteInfo<AssemblySymbol> template) where TMember : Symbol { // When the feature 'ImprovedOverloadCandidates' is enabled, we do not include methods for which the type arguments // violate the constraints of the method's type parameters. // Constraint violations apply to method in a method group, not to properties in a "property group". if (typeof(TMember) != typeof(MethodSymbol)) { return; } for (int f = 0; f < results.Count; ++f) { var result = results[f]; var member = (MethodSymbol)(Symbol)result.Member; // a constraint failure on the method trumps (for reporting purposes) a previously-detected // constraint failure on the constructed type of a parameter if ((result.Result.IsValid || result.Result.Kind == MemberResolutionKind.ConstructedParameterFailedConstraintCheck) && FailsConstraintChecks(member, out ArrayBuilder<TypeParameterDiagnosticInfo> constraintFailureDiagnosticsOpt, template)) { results[f] = new MemberResolutionResult<TMember>( result.Member, result.LeastOverriddenMember, MemberAnalysisResult.ConstraintFailure(constraintFailureDiagnosticsOpt.ToImmutableAndFree())); } } } #nullable enable private void RemoveCallingConventionMismatches<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, in CallingConventionInfo expectedConvention) where TMember : Symbol { if (typeof(TMember) != typeof(MethodSymbol)) { return; } Debug.Assert(!expectedConvention.CallKind.HasUnknownCallingConventionAttributeBits()); Debug.Assert(expectedConvention.UnmanagedCallingConventionTypes is not null); Debug.Assert(expectedConvention.UnmanagedCallingConventionTypes.IsEmpty || expectedConvention.CallKind == Cci.CallingConvention.Unmanaged); Debug.Assert(!_binder.IsEarlyAttributeBinder); if (_binder.InAttributeArgument || (_binder.Flags & BinderFlags.InContextualAttributeBinder) != 0) { // We're at a location where the unmanaged data might not yet been bound. This cannot be valid code // anyway, as attribute arguments can't be method references, so we'll just assume that the conventions // match, as there will be other errors that supersede these anyway return; } for (int i = 0; i < results.Count; i++) { var result = results[i]; var member = (MethodSymbol)(Symbol)result.Member; if (result.Result.IsValid) { // We're not in an attribute, so cycles shouldn't be possible var unmanagedCallersOnlyData = member.GetUnmanagedCallersOnlyAttributeData(forceComplete: true); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound) && !ReferenceEquals(unmanagedCallersOnlyData, UnmanagedCallersOnlyAttributeData.Uninitialized)); Cci.CallingConvention actualCallKind; ImmutableHashSet<INamedTypeSymbolInternal> actualUnmanagedCallingConventionTypes; if (unmanagedCallersOnlyData is null) { actualCallKind = member.CallingConvention; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; } else { // There's data from an UnmanagedCallersOnlyAttribute present, which takes precedence over the // CallKind bit in the method definition. We use the following rules to decode the attribute: // * If no types are specified, the CallKind is treated as Unmanaged, with no unmanaged calling convention types // * If there is one type specified, and that type is named CallConvCdecl, CallConvThiscall, CallConvStdcall, or // CallConvFastcall, the CallKind is treated as CDecl, ThisCall, Standard, or FastCall, respectively, with no // calling types. // * If multiple types are specified or the single type is not named one of the specially called out types above, // the CallKind is treated as Unmanaged, with the union of the types specified treated as calling convention types. var unmanagedCallingConventionTypes = unmanagedCallersOnlyData.CallingConventionTypes; Debug.Assert(unmanagedCallingConventionTypes.All(u => FunctionPointerTypeSymbol.IsCallingConventionModifier((NamedTypeSymbol)u))); switch (unmanagedCallingConventionTypes.Count) { case 0: actualCallKind = Cci.CallingConvention.Unmanaged; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; case 1: switch (unmanagedCallingConventionTypes.Single().Name) { case "CallConvCdecl": actualCallKind = Cci.CallingConvention.CDecl; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; case "CallConvStdcall": actualCallKind = Cci.CallingConvention.Standard; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; case "CallConvThiscall": actualCallKind = Cci.CallingConvention.ThisCall; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; case "CallConvFastcall": actualCallKind = Cci.CallingConvention.FastCall; actualUnmanagedCallingConventionTypes = ImmutableHashSet<INamedTypeSymbolInternal>.Empty; break; default: goto outerDefault; } break; default: outerDefault: actualCallKind = Cci.CallingConvention.Unmanaged; actualUnmanagedCallingConventionTypes = unmanagedCallingConventionTypes; break; } } // The rules for matching a calling convention are: // 1. The CallKinds must match exactly // 2. If the CallKind is Unmanaged, then the set of calling convention types must match exactly, ignoring order // and duplicates. We already have both sets in a HashSet, so we can just ensure they're the same length and // that everything from one set is in the other set. if (actualCallKind.HasUnknownCallingConventionAttributeBits() || !actualCallKind.IsCallingConvention(expectedConvention.CallKind)) { results[i] = makeWrongCallingConvention(result); continue; } if (expectedConvention.CallKind.IsCallingConvention(Cci.CallingConvention.Unmanaged)) { if (expectedConvention.UnmanagedCallingConventionTypes.Count != actualUnmanagedCallingConventionTypes.Count) { results[i] = makeWrongCallingConvention(result); continue; } foreach (var expectedModifier in expectedConvention.UnmanagedCallingConventionTypes) { if (!actualUnmanagedCallingConventionTypes.Contains(((CSharpCustomModifier)expectedModifier).ModifierSymbol)) { results[i] = makeWrongCallingConvention(result); break; } } } } } static MemberResolutionResult<TMember> makeWrongCallingConvention(MemberResolutionResult<TMember> result) => new MemberResolutionResult<TMember>(result.Member, result.LeastOverriddenMember, MemberAnalysisResult.WrongCallingConvention()); } #nullable disable private bool FailsConstraintChecks(MethodSymbol method, out ArrayBuilder<TypeParameterDiagnosticInfo> constraintFailureDiagnosticsOpt, CompoundUseSiteInfo<AssemblySymbol> template) { if (method.Arity == 0 || method.OriginalDefinition == (object)method) { constraintFailureDiagnosticsOpt = null; return false; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null; bool constraintsSatisfied = ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, location: NoLocation.Singleton, diagnostics: null, template), diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt: null, ref useSiteDiagnosticsBuilder); if (!constraintsSatisfied) { if (useSiteDiagnosticsBuilder != null) { diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder); useSiteDiagnosticsBuilder.Free(); } constraintFailureDiagnosticsOpt = diagnosticsBuilder; return true; } diagnosticsBuilder.Free(); useSiteDiagnosticsBuilder?.Free(); constraintFailureDiagnosticsOpt = null; return false; } /// <summary> /// Remove candidates to a delegate conversion where the method's return ref kind or return type is wrong. /// </summary> /// <param name="returnRefKind">The ref kind of the delegate's return, if known. This is only unknown in /// error scenarios, such as a delegate type that has no invoke method.</param> /// <param name="returnType">The return type of the delegate, if known. It isn't /// known when we're attempting to infer the return type of a method group for type inference.</param> private void RemoveDelegateConversionsWithWrongReturnType<TMember>( ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, RefKind? returnRefKind, TypeSymbol returnType, bool isFunctionPointerConversion) where TMember : Symbol { // When the feature 'ImprovedOverloadCandidates' is enabled, then a delegate conversion overload resolution // rejects candidates that have the wrong return ref kind or return type. // Delegate conversions apply to method in a method group, not to properties in a "property group". Debug.Assert(typeof(TMember) == typeof(MethodSymbol)); for (int f = 0; f < results.Count; ++f) { var result = results[f]; if (!result.Result.IsValid) { continue; } var method = (MethodSymbol)(Symbol)result.Member; bool returnsMatch; if (returnType is null || method.ReturnType.Equals(returnType, TypeCompareKind.AllIgnoreOptions)) { returnsMatch = true; } else if (returnRefKind == RefKind.None) { returnsMatch = Conversions.HasIdentityOrImplicitReferenceConversion(method.ReturnType, returnType, ref useSiteInfo); if (!returnsMatch && isFunctionPointerConversion) { returnsMatch = ConversionsBase.HasImplicitPointerToVoidConversion(method.ReturnType, returnType) || Conversions.HasImplicitPointerConversion(method.ReturnType, returnType, ref useSiteInfo); } } else { returnsMatch = false; } if (!returnsMatch) { results[f] = new MemberResolutionResult<TMember>( result.Member, result.LeastOverriddenMember, MemberAnalysisResult.WrongReturnType()); } else if (method.RefKind != returnRefKind) { results[f] = new MemberResolutionResult<TMember>( result.Member, result.LeastOverriddenMember, MemberAnalysisResult.WrongRefKind()); } } } private static Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> PartitionMembersByContainingType<TMember>(ArrayBuilder<TMember> members) where TMember : Symbol { Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMap = new Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>>(); for (int i = 0; i < members.Count; i++) { TMember member = members[i]; NamedTypeSymbol containingType = member.ContainingType; ArrayBuilder<TMember> builder; if (!containingTypeMap.TryGetValue(containingType, out builder)) { builder = ArrayBuilder<TMember>.GetInstance(); containingTypeMap[containingType] = builder; } builder.Add(member); } return containingTypeMap; } private static void ClearContainingTypeMap<TMember>(ref Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt) where TMember : Symbol { if ((object)containingTypeMapOpt != null) { foreach (ArrayBuilder<TMember> builder in containingTypeMapOpt.Values) { builder.Free(); } containingTypeMapOpt = null; } } private void AddConstructorToCandidateSet(MethodSymbol constructor, ArrayBuilder<MemberResolutionResult<MethodSymbol>> results, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Filter out constructors with unsupported metadata. if (constructor.HasUnsupportedMetadata) { Debug.Assert(!MemberAnalysisResult.UnsupportedMetadata().HasUseSiteDiagnosticToReportFor(constructor)); if (completeResults) { results.Add(new MemberResolutionResult<MethodSymbol>(constructor, constructor, MemberAnalysisResult.UnsupportedMetadata())); } return; } var normalResult = IsConstructorApplicableInNormalForm(constructor, arguments, completeResults, ref useSiteInfo); var result = normalResult; if (!normalResult.IsValid) { if (IsValidParams(constructor)) { var expandedResult = IsConstructorApplicableInExpandedForm(constructor, arguments, completeResults, ref useSiteInfo); if (expandedResult.IsValid || completeResults) { result = expandedResult; } } } // If the constructor has a use site diagnostic, we don't want to discard it because we'll have to report the diagnostic later. if (result.IsValid || completeResults || result.HasUseSiteDiagnosticToReportFor(constructor)) { results.Add(new MemberResolutionResult<MethodSymbol>(constructor, constructor, result)); } } private MemberAnalysisResult IsConstructorApplicableInNormalForm( MethodSymbol constructor, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var argumentAnalysis = AnalyzeArguments(constructor, arguments, isMethodGroupConversion: false, expanded: false); // Constructors are never involved in method group conversion. if (!argumentAnalysis.IsValid) { return MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis); } // Check after argument analysis, but before more complicated type inference and argument type validation. if (constructor.HasUseSiteError) { return MemberAnalysisResult.UseSiteError(); } var effectiveParameters = GetEffectiveParametersInNormalForm( constructor, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments: false); return IsApplicable( constructor, effectiveParameters, arguments, argumentAnalysis.ArgsToParamsOpt, isVararg: constructor.IsVararg, hasAnyRefOmittedArgument: false, ignoreOpenTypes: false, completeResults: completeResults, useSiteInfo: ref useSiteInfo); } private MemberAnalysisResult IsConstructorApplicableInExpandedForm( MethodSymbol constructor, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var argumentAnalysis = AnalyzeArguments(constructor, arguments, isMethodGroupConversion: false, expanded: true); if (!argumentAnalysis.IsValid) { return MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis); } // Check after argument analysis, but before more complicated type inference and argument type validation. if (constructor.HasUseSiteError) { return MemberAnalysisResult.UseSiteError(); } var effectiveParameters = GetEffectiveParametersInExpandedForm( constructor, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments: false); // A vararg ctor is never applicable in its expanded form because // it is never a params method. Debug.Assert(!constructor.IsVararg); var result = IsApplicable( constructor, effectiveParameters, arguments, argumentAnalysis.ArgsToParamsOpt, isVararg: false, hasAnyRefOmittedArgument: false, ignoreOpenTypes: false, completeResults: completeResults, useSiteInfo: ref useSiteInfo); return result.IsValid ? MemberAnalysisResult.ExpandedForm(result.ArgsToParamsOpt, result.ConversionsOpt, hasAnyRefOmittedArgument: false) : result; } private void AddMemberToCandidateSet<TMember>( TMember member, // method or property ArrayBuilder<MemberResolutionResult<TMember>> results, ArrayBuilder<TMember> members, ArrayBuilder<TypeWithAnnotations> typeArguments, BoundExpression receiverOpt, AnalyzedArguments arguments, bool completeResults, bool isMethodGroupConversion, bool allowRefOmittedArguments, Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt, bool inferWithDynamic, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowUnexpandedForm) where TMember : Symbol { // SPEC VIOLATION: // // The specification states that the method group that resulted from member lookup has // already had all the "override" methods removed; according to the spec, only the // original declaring type declarations remain. // // However, for IDE purposes ("go to definition") we *want* member lookup and overload // resolution to identify the overriding method. And the same for the purposes of code // generation. (For example, if you have 123.ToString() then we want to make a call to // Int32.ToString() directly, passing the int, rather than boxing and calling // Object.ToString() on the boxed object.) // // Therefore, in member lookup we do *not* eliminate the "override" methods, even though // the spec says to. When overload resolution is handed a method group, it contains both // the overriding methods and the overridden methods. // // This is bad; it means that we're going to be doing a lot of extra work. We don't need // to analyze every overload of every method to determine if it is applicable; we // already know that if one of them is applicable then they all will be. And we don't // want to be in a situation where we're comparing two identical methods for which is // "better" either. // // What we'll do here is first eliminate all the "duplicate" overriding methods. // However, because we want to give the result as the more derived method, we'll do the // opposite of what the member lookup spec says; we'll eliminate the less-derived // methods, not the more-derived overrides. This means that we'll have to be a bit more // clever in filtering out methods from less-derived classes later, but we'll cross that // bridge when we come to it. if (members.Count < 2) { // No hiding or overriding possible. } else if (containingTypeMapOpt == null) { if (MemberGroupContainsMoreDerivedOverride(members, member, checkOverrideContainingType: true, ref useSiteInfo)) { // Don't even add it to the result set. We'll add only the most-overriding members. return; } if (MemberGroupHidesByName(members, member, ref useSiteInfo)) { return; } } else if (containingTypeMapOpt.Count == 1) { // No hiding or overriding since all members are in the same type. } else { // NOTE: only check for overriding/hiding in subtypes of f.ContainingType. NamedTypeSymbol memberContainingType = member.ContainingType; foreach (var pair in containingTypeMapOpt) { NamedTypeSymbol otherType = pair.Key; if (otherType.IsDerivedFrom(memberContainingType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo)) { ArrayBuilder<TMember> others = pair.Value; if (MemberGroupContainsMoreDerivedOverride(others, member, checkOverrideContainingType: false, ref useSiteInfo)) { // Don't even add it to the result set. We'll add only the most-overriding members. return; } if (MemberGroupHidesByName(others, member, ref useSiteInfo)) { return; } } } } var leastOverriddenMember = (TMember)member.GetLeastOverriddenMember(_binder.ContainingType); // Filter out members with unsupported metadata. if (member.HasUnsupportedMetadata) { Debug.Assert(!MemberAnalysisResult.UnsupportedMetadata().HasUseSiteDiagnosticToReportFor(member)); if (completeResults) { results.Add(new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UnsupportedMetadata())); } return; } // First deal with eliminating generic-arity mismatches. // SPEC: If F is generic and M includes a type argument list, F is a candidate when: // SPEC: * F has the same number of method type parameters as were supplied in the type argument list, and // // This is specifying an impossible condition; the member lookup algorithm has already filtered // out methods from the method group that have the wrong generic arity. Debug.Assert(typeArguments.Count == 0 || typeArguments.Count == member.GetMemberArity()); // Second, we need to determine if the method is applicable in its normal form or its expanded form. var normalResult = (allowUnexpandedForm || !IsValidParams(leastOverriddenMember)) ? IsMemberApplicableInNormalForm( member, leastOverriddenMember, typeArguments, arguments, isMethodGroupConversion: isMethodGroupConversion, allowRefOmittedArguments: allowRefOmittedArguments, inferWithDynamic: inferWithDynamic, completeResults: completeResults, useSiteInfo: ref useSiteInfo) : default(MemberResolutionResult<TMember>); var result = normalResult; if (!normalResult.Result.IsValid) { // Whether a virtual method [indexer] is a "params" method [indexer] or not depends solely on how the // *original* declaration was declared. There are a variety of C# or MSIL // tricks you can pull to make overriding methods [indexers] inconsistent with overridden // methods [indexers] (or implementing methods [indexers] inconsistent with interfaces). if (!isMethodGroupConversion && IsValidParams(leastOverriddenMember)) { var expandedResult = IsMemberApplicableInExpandedForm( member, leastOverriddenMember, typeArguments, arguments, allowRefOmittedArguments: allowRefOmittedArguments, completeResults: completeResults, useSiteInfo: ref useSiteInfo); if (PreferExpandedFormOverNormalForm(normalResult.Result, expandedResult.Result)) { result = expandedResult; } } } // Retain candidates with use site diagnostics for later reporting. if (result.Result.IsValid || completeResults || result.HasUseSiteDiagnosticToReport) { results.Add(result); } else { result.Member.AddUseSiteInfo(ref useSiteInfo, addDiagnostics: false); } } // If the normal form is invalid and the expanded form is valid then obviously we prefer // the expanded form. However, there may be error-reporting situations where we // prefer to report the error on the expanded form rather than the normal form. // For example, if you have something like Goo<T>(params T[]) and a call // Goo(1, "") then the error for the normal form is "too many arguments" // and the error for the expanded form is "failed to infer T". Clearly the // expanded form error is better. private static bool PreferExpandedFormOverNormalForm(MemberAnalysisResult normalResult, MemberAnalysisResult expandedResult) { Debug.Assert(!normalResult.IsValid); if (expandedResult.IsValid) { return true; } switch (normalResult.Kind) { case MemberResolutionKind.RequiredParameterMissing: case MemberResolutionKind.NoCorrespondingParameter: switch (expandedResult.Kind) { case MemberResolutionKind.BadArgumentConversion: case MemberResolutionKind.NameUsedForPositional: case MemberResolutionKind.TypeInferenceFailed: case MemberResolutionKind.TypeInferenceExtensionInstanceArgument: case MemberResolutionKind.ConstructedParameterFailedConstraintCheck: case MemberResolutionKind.NoCorrespondingNamedParameter: case MemberResolutionKind.UseSiteError: case MemberResolutionKind.BadNonTrailingNamedArgument: case MemberResolutionKind.DuplicateNamedArgument: return true; } break; } return false; } // We need to know if this is a valid formal parameter list with a parameter array // as the final formal parameter. We might be in an error recovery scenario // where the params array is not an array type. public static bool IsValidParams(Symbol member) { // A varargs method is never a valid params method. if (member.GetIsVararg()) { return false; } int paramCount = member.GetParameterCount(); if (paramCount == 0) { return false; } ParameterSymbol final = member.GetParameters().Last(); return IsValidParamsParameter(final); } public static bool IsValidParamsParameter(ParameterSymbol final) { Debug.Assert((object)final == final.ContainingSymbol.GetParameters().Last()); return final.IsParams && ((ParameterSymbol)final.OriginalDefinition).Type.IsSZArray(); } /// <summary> /// Does <paramref name="moreDerivedOverride"/> override <paramref name="member"/> or the /// thing that it originally overrides, but in a more derived class? /// </summary> /// <param name="checkOverrideContainingType">Set to false if the caller has already checked that /// <paramref name="moreDerivedOverride"/> is in a type that derives from the type containing /// <paramref name="member"/>.</param> private static bool IsMoreDerivedOverride( Symbol member, Symbol moreDerivedOverride, bool checkOverrideContainingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!moreDerivedOverride.IsOverride || checkOverrideContainingType && !moreDerivedOverride.ContainingType.IsDerivedFrom(member.ContainingType, TypeCompareKind.ConsiderEverything, ref useSiteInfo) || !MemberSignatureComparer.SloppyOverrideComparer.Equals(member, moreDerivedOverride)) { // Easy out. return false; } // Rather than following the member.GetOverriddenMember() chain, we check to see if both // methods ultimately override the same original method. This addresses issues in binary compat // scenarios where the override chain may skip some steps. // See https://github.com/dotnet/roslyn/issues/45798 for an example. return moreDerivedOverride.GetLeastOverriddenMember(accessingTypeOpt: null).OriginalDefinition == member.GetLeastOverriddenMember(accessingTypeOpt: null).OriginalDefinition; } /// <summary> /// Does the member group <paramref name="members"/> contain an override of <paramref name="member"/> or the method it /// overrides, but in a more derived type? /// </summary> /// <param name="checkOverrideContainingType">Set to false if the caller has already checked that /// <paramref name="members"/> are all in a type that derives from the type containing /// <paramref name="member"/>.</param> private static bool MemberGroupContainsMoreDerivedOverride<TMember>( ArrayBuilder<TMember> members, TMember member, bool checkOverrideContainingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { if (!member.IsVirtual && !member.IsAbstract && !member.IsOverride) { return false; } if (!member.ContainingType.IsClassType()) { return false; } for (var i = 0; i < members.Count; ++i) { if (IsMoreDerivedOverride(member: member, moreDerivedOverride: members[i], checkOverrideContainingType: checkOverrideContainingType, ref useSiteInfo)) { return true; } } return false; } private static bool MemberGroupHidesByName<TMember>(ArrayBuilder<TMember> members, TMember member, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { NamedTypeSymbol memberContainingType = member.ContainingType; foreach (var otherMember in members) { NamedTypeSymbol otherContainingType = otherMember.ContainingType; if (HidesByName(otherMember) && otherContainingType.IsDerivedFrom(memberContainingType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo)) { return true; } } return false; } /// <remarks> /// This is specifically a private helper function (rather than a public property or extension method) /// because applying this predicate to a non-method member doesn't have a clear meaning. The goal was /// simply to avoid repeating ad-hoc code in a group of related collections. /// </remarks> private static bool HidesByName(Symbol member) { switch (member.Kind) { case SymbolKind.Method: return ((MethodSymbol)member).HidesBaseMethodsByName; case SymbolKind.Property: return ((PropertySymbol)member).HidesBasePropertiesByName; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private void RemoveInaccessibleTypeArguments<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { for (int f = 0; f < results.Count; ++f) { var result = results[f]; if (result.Result.IsValid && !TypeArgumentsAccessible(result.Member.GetMemberTypeArgumentsNoUseSiteDiagnostics(), ref useSiteInfo)) { results[f] = new MemberResolutionResult<TMember>(result.Member, result.LeastOverriddenMember, MemberAnalysisResult.InaccessibleTypeArgument()); } } } private bool TypeArgumentsAccessible(ImmutableArray<TypeSymbol> typeArguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { foreach (TypeSymbol arg in typeArguments) { if (!_binder.IsAccessible(arg, ref useSiteInfo)) return false; } return true; } private static void RemoveLessDerivedMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { // 7.6.5.1 Method invocations // SPEC: For each method C.F in the set, where C is the type in which the method F is declared, // SPEC: all methods declared in a base type of C are removed from the set. Furthermore, if C // SPEC: is a class type other than object, all methods declared in an interface type are removed // SPEC: from the set. (This latter rule only has affect when the method group was the result of // SPEC: a member lookup on a type parameter having an effective base class other than object // SPEC: and a non-empty effective interface set.) // This is going to get a bit complicated. // // Call the "original declaring type" of a method the type which first declares the // method, rather than overriding it. // // The specification states that the method group that resulted from member lookup has // already had all the "override" methods removed; according to the spec, only the // original declaring type declarations remain. This means that when we do this // filtering, we're not suppose to remove methods of a base class just because there was // some override in a more derived class. Whether there is an override or not is an // implementation detail of the derived class; it shouldn't affect overload resolution. // The point of overload resolution is to determine the *slot* that is going to be // invoked, not the specific overriding method body. // // However, for IDE purposes ("go to definition") we *want* member lookup and overload // resolution to identify the overriding method. And the same for the purposes of code // generation. (For example, if you have 123.ToString() then we want to make a call to // Int32.ToString() directly, passing the int, rather than boxing and calling // Object.ToString() on the boxed object.) // // Therefore, in member lookup we do *not* eliminate the "override" methods, even though // the spec says to. When overload resolution is handed a method group, it contains both // the overriding methods and the overridden methods. We eliminate the *overridden* // methods during applicable candidate set construction. // // Let's look at an example. Suppose we have in the method group: // // virtual Animal.M(T1), // virtual Mammal.M(T2), // virtual Mammal.M(T3), // override Giraffe.M(T1), // override Giraffe.M(T2) // // According to the spec, the override methods should not even be there. But they are. // // When we constructed the applicable candidate set we already removed everything that // was less-overridden. So the applicable candidate set contains: // // virtual Mammal.M(T3), // override Giraffe.M(T1), // override Giraffe.M(T2) // // Again, that is not what should be there; what should be there are the three non- // overriding methods. For the purposes of removing more stuff, we need to behave as // though that's what was there. // // The presence of Giraffe.M(T2) does *not* justify the removal of Mammal.M(T3); it is // not to be considered a method of Giraffe, but rather a method of Mammal for the // purposes of removing other methods. // // However, the presence of Mammal.M(T3) does justify the removal of Giraffe.M(T1). Why? // Because the presence of Mammal.M(T3) justifies the removal of Animal.M(T1), and that // is what is supposed to be in the set instead of Giraffe.M(T1). // // The resulting candidate set after the filtering according to the spec should be: // // virtual Mammal.M(T3), virtual Mammal.M(T2) // // But what we actually want to be there is: // // virtual Mammal.M(T3), override Giraffe.M(T2) // // So that a "go to definition" (should the latter be chosen as best) goes to the override. // // OK, so what are we going to do here? // // First, deal with this business about object and interfaces. RemoveAllInterfaceMembers(results); // Second, apply the rule that we eliminate any method whose *original declaring type* // is a base type of the original declaring type of any other method. // Note that this (and several of the other algorithms in overload resolution) is // O(n^2). (We expect that n will be relatively small. Also, we're trying to do these // algorithms without allocating hardly any additional memory, which pushes us towards // walking data structures multiple times rather than caching information about them.) for (int f = 0; f < results.Count; ++f) { var result = results[f]; // As in dev12, we want to drop use site errors from less-derived types. // NOTE: Because of use site warnings, a result with a diagnostic to report // might not have kind UseSiteError. This could result in a kind being // switched to LessDerived (i.e. loss of information), but it is the most // straightforward way to suppress use site diagnostics from less-derived // members. if (!(result.Result.IsValid || result.HasUseSiteDiagnosticToReport)) { continue; } // Note that we are doing something which appears a bit dodgy here: we're modifying // the validity of elements of the set while inside an outer loop which is filtering // the set based on validity. This means that we could remove an item from the set // that we ought to be processing later. However, because the "is a base type of" // relationship is transitive, that's OK. For example, suppose we have members // Cat.M, Mammal.M and Animal.M in the set. The first time through the outer loop we // eliminate Mammal.M and Animal.M, and therefore we never process Mammal.M the // second time through the outer loop. That's OK, because we have already done the // work necessary to eliminate methods on base types of Mammal when we eliminated // methods on base types of Cat. if (IsLessDerivedThanAny(result.LeastOverriddenMember.ContainingType, results, ref useSiteInfo)) { results[f] = new MemberResolutionResult<TMember>(result.Member, result.LeastOverriddenMember, MemberAnalysisResult.LessDerived()); } } } // Is this type a base type of any valid method on the list? private static bool IsLessDerivedThanAny<TMember>(TypeSymbol type, ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { for (int f = 0; f < results.Count; ++f) { var result = results[f]; if (!result.Result.IsValid) { continue; } var currentType = result.LeastOverriddenMember.ContainingType; // For purposes of removing less-derived methods, object is considered to be a base // type of any type other than itself. // UNDONE: Do we also need to special-case System.Array being a base type of array, // and so on? if (type.SpecialType == SpecialType.System_Object && currentType.SpecialType != SpecialType.System_Object) { return true; } if (currentType.IsInterfaceType() && type.IsInterfaceType() && currentType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).Contains((NamedTypeSymbol)type)) { return true; } else if (currentType.IsClassType() && type.IsClassType() && currentType.IsDerivedFrom(type, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo)) { return true; } } return false; } private static void RemoveAllInterfaceMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results) where TMember : Symbol { // Consider the following case: // // interface IGoo { string ToString(); } // class C { public override string ToString() { whatever } } // class D : C, IGoo // { // public override string ToString() { whatever } // string IGoo.ToString() { whatever } // } // ... // void M<U>(U u) where U : C, IGoo { u.ToString(); } // ??? // ... // M(new D()); // // What should overload resolution do on the call to u.ToString()? // // We will have IGoo.ToString and C.ToString (which is an override of object.ToString) // in the candidate set. Does the rule apply to eliminate all interface methods? NO. The // rule only applies if the candidate set contains a method which originally came from a // class type other than object. The method C.ToString is the "slot" for // object.ToString, so this counts as coming from object. M should call the explicit // interface implementation. // // If, by contrast, that said // // class C { public new virtual string ToString() { whatever } } // // Then the candidate set contains a method ToString which comes from a class type other // than object. The interface method should be eliminated and M should call virtual // method C.ToString(). bool anyClassOtherThanObject = false; for (int f = 0; f < results.Count; f++) { var result = results[f]; if (!result.Result.IsValid) { continue; } var type = result.LeastOverriddenMember.ContainingType; if (type.IsClassType() && type.GetSpecialTypeSafe() != SpecialType.System_Object) { anyClassOtherThanObject = true; break; } } if (!anyClassOtherThanObject) { return; } for (int f = 0; f < results.Count; f++) { var result = results[f]; if (!result.Result.IsValid) { continue; } var member = result.Member; if (member.ContainingType.IsInterfaceType()) { results[f] = new MemberResolutionResult<TMember>(member, result.LeastOverriddenMember, MemberAnalysisResult.LessDerived()); } } } // Perform instance constructor overload resolution, storing the results into "results". If // completeResults is false, then invalid results don't have to be stored. The results will // still contain all possible successful resolution. private void PerformObjectCreationOverloadResolution( ArrayBuilder<MemberResolutionResult<MethodSymbol>> results, ImmutableArray<MethodSymbol> constructors, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The instance constructor to invoke is determined using the overload resolution // SPEC: rules of 7.5.3. The set of candidate instance constructors consists of all // SPEC: accessible instance constructors declared in T which are applicable with respect // SPEC: to A (7.5.3.1). If the set of candidate instance constructors is empty, or if a // SPEC: single best instance constructor cannot be identified, a binding-time error occurs. foreach (MethodSymbol constructor in constructors) { AddConstructorToCandidateSet(constructor, results, arguments, completeResults, ref useSiteInfo); } ReportUseSiteInfo(results, ref useSiteInfo); // The best method of the set of candidate methods is identified. If a single best // method cannot be identified, the method invocation is ambiguous, and a binding-time // error occurs. RemoveWorseMembers(results, arguments, ref useSiteInfo); return; } private static void ReportUseSiteInfo<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { foreach (MemberResolutionResult<TMember> result in results) { result.Member.AddUseSiteInfo(ref useSiteInfo, addDiagnostics: result.HasUseSiteDiagnosticToReport); } } private int GetTheBestCandidateIndex<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, AnalyzedArguments arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { int currentBestIndex = -1; for (int index = 0; index < results.Count; index++) { if (!results[index].IsValid) { continue; } // Assume that the current candidate is the best if we don't have any if (currentBestIndex == -1) { currentBestIndex = index; } else if (results[currentBestIndex].Member == results[index].Member) { currentBestIndex = -1; } else { var better = BetterFunctionMember(results[currentBestIndex], results[index], arguments.Arguments, ref useSiteInfo); if (better == BetterResult.Right) { // The current best is worse currentBestIndex = index; } else if (better != BetterResult.Left) { // The current best is not better currentBestIndex = -1; } } } // Make sure that every candidate up to the current best is worse for (int index = 0; index < currentBestIndex; index++) { if (!results[index].IsValid) { continue; } if (results[currentBestIndex].Member == results[index].Member) { return -1; } var better = BetterFunctionMember(results[currentBestIndex], results[index], arguments.Arguments, ref useSiteInfo); if (better != BetterResult.Left) { // The current best is not better return -1; } } return currentBestIndex; } private void RemoveWorseMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, AnalyzedArguments arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { // SPEC: Given the set of applicable candidate function members, the best function member in // SPEC: that set is located. Otherwise, the best function member is the one function member // SPEC: that is better than all other function members with respect to the given argument // SPEC: list. // Note that the above rules require that the best member be *better* than all other // applicable candidates. Consider three overloads such that: // // 3 beats 2 // 2 beats 1 // 3 is neither better than nor worse than 1 // // It is tempting to say that overload 3 is the winner because it is the one method // that beats something, and is beaten by nothing. But that would be incorrect; // method 3 needs to beat all other methods, including method 1. // // We work up a full analysis of every member of the set. If it is worse than anything // then we need to do no more work; we know it cannot win. But it is also possible that // it is not worse than anything but not better than everything. if (SingleValidResult(results)) { return; } // See if we have a winner, otherwise we might need to perform additional analysis // in order to improve diagnostics int bestIndex = GetTheBestCandidateIndex(results, arguments, ref useSiteInfo); if (bestIndex != -1) { // Mark all other candidates as worse for (int index = 0; index < results.Count; index++) { if (results[index].IsValid && index != bestIndex) { results[index] = results[index].Worse(); } } return; } const int unknown = 0; const int worseThanSomething = 1; const int notBetterThanEverything = 2; var worse = ArrayBuilder<int>.GetInstance(results.Count, unknown); int countOfNotBestCandidates = 0; int notBestIdx = -1; for (int c1Idx = 0; c1Idx < results.Count; c1Idx++) { var c1Result = results[c1Idx]; // If we already know this is worse than something else, no need to check again. if (!c1Result.IsValid || worse[c1Idx] == worseThanSomething) { continue; } for (int c2Idx = 0; c2Idx < results.Count; c2Idx++) { var c2Result = results[c2Idx]; if (!c2Result.IsValid || c1Idx == c2Idx || c1Result.Member == c2Result.Member) { continue; } var better = BetterFunctionMember(c1Result, c2Result, arguments.Arguments, ref useSiteInfo); if (better == BetterResult.Left) { worse[c2Idx] = worseThanSomething; } else if (better == BetterResult.Right) { worse[c1Idx] = worseThanSomething; break; } } if (worse[c1Idx] == unknown) { // c1 was not worse than anything worse[c1Idx] = notBetterThanEverything; countOfNotBestCandidates++; notBestIdx = c1Idx; } } if (countOfNotBestCandidates == 0) { for (int i = 0; i < worse.Count; ++i) { Debug.Assert(!results[i].IsValid || worse[i] != unknown); if (worse[i] == worseThanSomething) { results[i] = results[i].Worse(); } } } else if (countOfNotBestCandidates == 1) { for (int i = 0; i < worse.Count; ++i) { Debug.Assert(!results[i].IsValid || worse[i] != unknown); if (worse[i] == worseThanSomething) { // Mark those candidates, that are worse than the single notBest candidate, as Worst in order to improve error reporting. results[i] = BetterResult.Left == BetterFunctionMember(results[notBestIdx], results[i], arguments.Arguments, ref useSiteInfo) ? results[i].Worst() : results[i].Worse(); } else { Debug.Assert(worse[i] != notBetterThanEverything || i == notBestIdx); } } Debug.Assert(worse[notBestIdx] == notBetterThanEverything); results[notBestIdx] = results[notBestIdx].Worse(); } else { Debug.Assert(countOfNotBestCandidates > 1); for (int i = 0; i < worse.Count; ++i) { Debug.Assert(!results[i].IsValid || worse[i] != unknown); if (worse[i] == worseThanSomething) { // Mark those candidates, that are worse than something, as Worst in order to improve error reporting. results[i] = results[i].Worst(); } else if (worse[i] == notBetterThanEverything) { results[i] = results[i].Worse(); } } } worse.Free(); } /// <summary> /// Returns the parameter type (considering params). /// </summary> private TypeSymbol GetParameterType(ParameterSymbol parameter, MemberAnalysisResult result) { var type = parameter.Type; if (result.Kind == MemberResolutionKind.ApplicableInExpandedForm && parameter.IsParams && type.IsSZArray()) { return ((ArrayTypeSymbol)type).ElementType; } else { return type; } } /// <summary> /// Returns the parameter corresponding to the given argument index. /// </summary> private static ParameterSymbol GetParameter(int argIndex, MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters) { int paramIndex = result.ParameterFromArgument(argIndex); return parameters[paramIndex]; } #nullable enable private BetterResult BetterFunctionMember<TMember>( MemberResolutionResult<TMember> m1, MemberResolutionResult<TMember> m2, ArrayBuilder<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { Debug.Assert(m1.Result.IsValid); Debug.Assert(m2.Result.IsValid); Debug.Assert(arguments != null); // Prefer overloads that did not use the inferred type of lambdas or method groups // to infer generic method type arguments or to convert arguments. switch (RequiredFunctionType(m1), RequiredFunctionType(m2)) { case (false, true): return BetterResult.Left; case (true, false): return BetterResult.Right; } // Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method/property on an instance of a COM imported type. // We should have ignored the 'ref' on the parameter while determining the applicability of argument for the given method call. // As per Devdiv Bug #696573: '[Interop] Com omit ref overload resolution is incorrect', we must prefer non-ref omitted methods over ref omitted methods // when determining the BetterFunctionMember. // During argument rewriting, we will replace the argument value with a temporary local and pass that local by reference. bool hasAnyRefOmittedArgument1 = m1.Result.HasAnyRefOmittedArgument; bool hasAnyRefOmittedArgument2 = m2.Result.HasAnyRefOmittedArgument; if (hasAnyRefOmittedArgument1 != hasAnyRefOmittedArgument2) { return hasAnyRefOmittedArgument1 ? BetterResult.Right : BetterResult.Left; } else { return BetterFunctionMember(m1, m2, arguments, considerRefKinds: hasAnyRefOmittedArgument1, useSiteInfo: ref useSiteInfo); } } private BetterResult BetterFunctionMember<TMember>( MemberResolutionResult<TMember> m1, MemberResolutionResult<TMember> m2, ArrayBuilder<BoundExpression> arguments, bool considerRefKinds, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { Debug.Assert(m1.Result.IsValid); Debug.Assert(m2.Result.IsValid); Debug.Assert(arguments != null); // SPEC: // Parameter lists for each of the candidate function members are constructed in the following way: // The expanded form is used if the function member was applicable only in the expanded form. // Optional parameters with no corresponding arguments are removed from the parameter list // The parameters are reordered so that they occur at the same position as the corresponding argument in the argument list. // We don't actually create these lists, for efficiency reason. But we iterate over the arguments // and get the correspond parameter types. BetterResult result = BetterResult.Neither; bool okToDowngradeResultToNeither = false; bool ignoreDowngradableToNeither = false; // Given an argument list A with a set of argument expressions { E1, E2, ..., EN } and two // applicable function members MP and MQ with parameter types { P1, P2, ..., PN } and { Q1, Q2, ..., QN }, // MP is defined to be a better function member than MQ if // for each argument, the implicit conversion from EX to QX is not better than the // implicit conversion from EX to PX, and for at least one argument, the conversion from // EX to PX is better than the conversion from EX to QX. var m1LeastOverriddenParameters = m1.LeastOverriddenMember.GetParameters(); var m2LeastOverriddenParameters = m2.LeastOverriddenMember.GetParameters(); bool allSame = true; // Are all parameter types equivalent by identify conversions, ignoring Task-like differences? int i; for (i = 0; i < arguments.Count; ++i) { var argumentKind = arguments[i].Kind; // If these are both applicable varargs methods and we're looking at the __arglist argument // then clearly neither of them is going to be better in this argument. if (argumentKind == BoundKind.ArgListOperator) { Debug.Assert(i == arguments.Count - 1); Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg()); continue; } var parameter1 = GetParameter(i, m1.Result, m1LeastOverriddenParameters); var type1 = GetParameterType(parameter1, m1.Result); var parameter2 = GetParameter(i, m2.Result, m2LeastOverriddenParameters); var type2 = GetParameterType(parameter2, m2.Result); bool okToDowngradeToNeither; BetterResult r; r = BetterConversionFromExpression(arguments[i], type1, m1.Result.ConversionForArg(i), parameter1.RefKind, type2, m2.Result.ConversionForArg(i), parameter2.RefKind, considerRefKinds, ref useSiteInfo, out okToDowngradeToNeither); var type1Normalized = type1; var type2Normalized = type2; // Normalizing task types can cause attributes to be bound on the type, // and attribute arguments may call overloaded methods in error cases. // To avoid a stack overflow, we must not normalize task types within attribute arguments. if (!_binder.InAttributeArgument) { type1Normalized = type1.NormalizeTaskTypes(Compilation); type2Normalized = type2.NormalizeTaskTypes(Compilation); } if (r == BetterResult.Neither) { if (allSame && Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, ref useSiteInfo).Kind != ConversionKind.Identity) { allSame = false; } // We learned nothing from this one. Keep going. continue; } if (Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, ref useSiteInfo).Kind != ConversionKind.Identity) { allSame = false; } // One of them was better, even if identical up to Task-likeness. Does that contradict a previous result or add a new fact? if (result == BetterResult.Neither) { if (!(ignoreDowngradableToNeither && okToDowngradeToNeither)) { // Add a new fact; we know that one of them is better when we didn't know that before. result = r; okToDowngradeResultToNeither = okToDowngradeToNeither; } } else if (result != r) { // We previously got, say, Left is better in one place. Now we have that Right // is better in one place. We know we can bail out at this point; neither is // going to be better than the other. // But first, let's see if we can ignore the ambiguity due to an undocumented legacy behavior of the compiler. // This is not part of the language spec. if (okToDowngradeResultToNeither) { if (okToDowngradeToNeither) { // Ignore the new information and the current result. Going forward, // continue ignoring any downgradable information. result = BetterResult.Neither; okToDowngradeResultToNeither = false; ignoreDowngradableToNeither = true; continue; } else { // Current result can be ignored, but the new information cannot be ignored. // Let's ignore the current result. result = r; okToDowngradeResultToNeither = false; continue; } } else if (okToDowngradeToNeither) { // Current result cannot be ignored, but the new information can be ignored. // Let's ignore it and continue with the current result. continue; } result = BetterResult.Neither; break; } else { Debug.Assert(result == r); Debug.Assert(result == BetterResult.Left || result == BetterResult.Right); okToDowngradeResultToNeither = (okToDowngradeResultToNeither && okToDowngradeToNeither); } } // Was one unambiguously better? Return it. if (result != BetterResult.Neither) { return result; } // In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are // equivalent ignoring Task-like differences (i.e. each Pi has an identity conversion to the corresponding Qi), the // following tie-breaking rules are applied, in order, to determine the better function // member. int m1ParameterCount; int m2ParameterCount; int m1ParametersUsedIncludingExpansionAndOptional; int m2ParametersUsedIncludingExpansionAndOptional; GetParameterCounts(m1, arguments, out m1ParameterCount, out m1ParametersUsedIncludingExpansionAndOptional); GetParameterCounts(m2, arguments, out m2ParameterCount, out m2ParametersUsedIncludingExpansionAndOptional); // We might have got out of the loop above early and allSame isn't completely calculated. // We need to ensure that we are not going to skip over the next 'if' because of that. // One way we can break out of the above loop early is when the corresponding method parameters have identical types // but different ref kinds. See RefOmittedComCall_OverloadResolution_MultipleArguments_ErrorCases for an example. if (allSame && m1ParametersUsedIncludingExpansionAndOptional == m2ParametersUsedIncludingExpansionAndOptional) { // Complete comparison for the remaining parameter types for (i = i + 1; i < arguments.Count; ++i) { var argumentKind = arguments[i].Kind; // If these are both applicable varargs methods and we're looking at the __arglist argument // then clearly neither of them is going to be better in this argument. if (argumentKind == BoundKind.ArgListOperator) { Debug.Assert(i == arguments.Count - 1); Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg()); continue; } var parameter1 = GetParameter(i, m1.Result, m1LeastOverriddenParameters); var type1 = GetParameterType(parameter1, m1.Result); var parameter2 = GetParameter(i, m2.Result, m2LeastOverriddenParameters); var type2 = GetParameterType(parameter2, m2.Result); var type1Normalized = type1; var type2Normalized = type2; if (!_binder.InAttributeArgument) { type1Normalized = type1.NormalizeTaskTypes(Compilation); type2Normalized = type2.NormalizeTaskTypes(Compilation); } if (Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, ref useSiteInfo).Kind != ConversionKind.Identity) { allSame = false; break; } } } // SPEC VIOLATION: When checking for matching parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN}, // native compiler includes types of optional parameters. We partially duplicate this behavior // here by comparing the number of parameters used taking params expansion and // optional parameters into account. if (!allSame || m1ParametersUsedIncludingExpansionAndOptional != m2ParametersUsedIncludingExpansionAndOptional) { // SPEC VIOLATION: Even when parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are // not equivalent, we have tie-breaking rules. // // Relevant code in the native compiler is at the end of // BetterTypeEnum ExpressionBinder::WhichMethodIsBetter( // const CandidateFunctionMember &node1, // const CandidateFunctionMember &node2, // Type* pTypeThrough, // ArgInfos*args) // if (m1ParametersUsedIncludingExpansionAndOptional != m2ParametersUsedIncludingExpansionAndOptional) { if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { if (m2.Result.Kind != MemberResolutionKind.ApplicableInExpandedForm) { return BetterResult.Right; } } else if (m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { Debug.Assert(m1.Result.Kind != MemberResolutionKind.ApplicableInExpandedForm); return BetterResult.Left; } // Here, if both methods needed to use optionals to fill in the signatures, // then we are ambiguous. Otherwise, take the one that didn't need any // optionals. if (m1ParametersUsedIncludingExpansionAndOptional == arguments.Count) { return BetterResult.Left; } else if (m2ParametersUsedIncludingExpansionAndOptional == arguments.Count) { return BetterResult.Right; } } return PreferValOverInOrRefInterpolatedHandlerParameters(arguments, m1, m1LeastOverriddenParameters, m2, m2LeastOverriddenParameters); } // If MP is a non-generic method and MQ is a generic method, then MP is better than MQ. if (m1.Member.GetMemberArity() == 0) { if (m2.Member.GetMemberArity() > 0) { return BetterResult.Left; } } else if (m2.Member.GetMemberArity() == 0) { return BetterResult.Right; } // Otherwise, if MP is applicable in its normal form and MQ has a params array and is // applicable only in its expanded form, then MP is better than MQ. if (m1.Result.Kind == MemberResolutionKind.ApplicableInNormalForm && m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { return BetterResult.Left; } if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm && m2.Result.Kind == MemberResolutionKind.ApplicableInNormalForm) { return BetterResult.Right; } // SPEC ERROR: The spec has a minor error in working here. It says: // // Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ. // This can occur if both methods have params arrays and are applicable only in their // expanded forms. // // The explanatory text actually should be normative. It should say: // // Otherwise, if both methods have params arrays and are applicable only in their // expanded forms, and if MP has more declared parameters than MQ, then MP is better than MQ. if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm && m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { if (m1ParameterCount > m2ParameterCount) { return BetterResult.Left; } if (m1ParameterCount < m2ParameterCount) { return BetterResult.Right; } } // Otherwise if all parameters of MP have a corresponding argument whereas default // arguments need to be substituted for at least one optional parameter in MQ then MP is // better than MQ. bool hasAll1 = m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm || m1ParameterCount == arguments.Count; bool hasAll2 = m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm || m2ParameterCount == arguments.Count; if (hasAll1 && !hasAll2) { return BetterResult.Left; } if (!hasAll1 && hasAll2) { return BetterResult.Right; } // Otherwise, if MP has more specific parameter types than MQ, then MP is better than // MQ. Let {R1, R2, …, RN} and {S1, S2, …, SN} represent the uninstantiated and // unexpanded parameter types of MP and MQ. MP's parameter types are more specific than // MQ's if, for each parameter, RX is not less specific than SX, and, for at least one // parameter, RX is more specific than SX // NB: OriginalDefinition, not ConstructedFrom. Substitutions into containing symbols // must also be ignored for this tie-breaker. var uninst1 = ArrayBuilder<TypeSymbol>.GetInstance(); var uninst2 = ArrayBuilder<TypeSymbol>.GetInstance(); var m1Original = m1.LeastOverriddenMember.OriginalDefinition.GetParameters(); var m2Original = m2.LeastOverriddenMember.OriginalDefinition.GetParameters(); for (i = 0; i < arguments.Count; ++i) { // If these are both applicable varargs methods and we're looking at the __arglist argument // then clearly neither of them is going to be better in this argument. if (arguments[i].Kind == BoundKind.ArgListOperator) { Debug.Assert(i == arguments.Count - 1); Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg()); continue; } var parameter1 = GetParameter(i, m1.Result, m1Original); uninst1.Add(GetParameterType(parameter1, m1.Result)); var parameter2 = GetParameter(i, m2.Result, m2Original); uninst2.Add(GetParameterType(parameter2, m2.Result)); } result = MoreSpecificType(uninst1, uninst2, ref useSiteInfo); uninst1.Free(); uninst2.Free(); if (result != BetterResult.Neither) { return result; } // UNDONE: Otherwise if one member is a non-lifted operator and the other is a lifted // operator, the non-lifted one is better. // Otherwise: Position in interactive submission chain. The last definition wins. if (m1.Member.ContainingType.TypeKind == TypeKind.Submission && m2.Member.ContainingType.TypeKind == TypeKind.Submission) { // script class is always defined in source: var compilation1 = m1.Member.DeclaringCompilation; var compilation2 = m2.Member.DeclaringCompilation; int submissionId1 = compilation1.GetSubmissionSlotIndex(); int submissionId2 = compilation2.GetSubmissionSlotIndex(); if (submissionId1 > submissionId2) { return BetterResult.Left; } if (submissionId1 < submissionId2) { return BetterResult.Right; } } // Otherwise, if one has fewer custom modifiers, that is better int m1ModifierCount = m1.LeastOverriddenMember.CustomModifierCount(); int m2ModifierCount = m2.LeastOverriddenMember.CustomModifierCount(); if (m1ModifierCount != m2ModifierCount) { return (m1ModifierCount < m2ModifierCount) ? BetterResult.Left : BetterResult.Right; } // Otherwise, prefer methods with 'val' parameters over 'in' parameters and over 'ref' parameters when the argument is an interpolated string handler. return PreferValOverInOrRefInterpolatedHandlerParameters(arguments, m1, m1LeastOverriddenParameters, m2, m2LeastOverriddenParameters); } /// <summary> /// Returns true if the overload required a function type conversion to infer /// generic method type arguments or to convert to parameter types. /// </summary> private static bool RequiredFunctionType<TMember>(MemberResolutionResult<TMember> m) where TMember : Symbol { Debug.Assert(m.Result.IsValid); if (m.HasTypeArgumentInferredFromFunctionType) { return true; } var conversionsOpt = m.Result.ConversionsOpt; if (conversionsOpt.IsDefault) { return false; } return conversionsOpt.Any(c => c.Kind == ConversionKind.FunctionType); } private static BetterResult PreferValOverInOrRefInterpolatedHandlerParameters<TMember>( ArrayBuilder<BoundExpression> arguments, MemberResolutionResult<TMember> m1, ImmutableArray<ParameterSymbol> parameters1, MemberResolutionResult<TMember> m2, ImmutableArray<ParameterSymbol> parameters2) where TMember : Symbol { BetterResult valOverInOrRefInterpolatedHandlerPreference = BetterResult.Neither; for (int i = 0; i < arguments.Count; ++i) { if (arguments[i].Kind != BoundKind.ArgListOperator) { var p1 = GetParameter(i, m1.Result, parameters1); var p2 = GetParameter(i, m2.Result, parameters2); bool isInterpolatedStringHandlerConversion = false; if (m1.IsValid && m2.IsValid) { var c1 = m1.Result.ConversionForArg(i); var c2 = m2.Result.ConversionForArg(i); isInterpolatedStringHandlerConversion = c1.IsInterpolatedStringHandler && c2.IsInterpolatedStringHandler; Debug.Assert(!isInterpolatedStringHandlerConversion || arguments[i] is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }); } if (p1.RefKind == RefKind.None && isAcceptableRefMismatch(p2.RefKind, isInterpolatedStringHandlerConversion)) { if (valOverInOrRefInterpolatedHandlerPreference == BetterResult.Right) { return BetterResult.Neither; } else { valOverInOrRefInterpolatedHandlerPreference = BetterResult.Left; } } else if (p2.RefKind == RefKind.None && isAcceptableRefMismatch(p1.RefKind, isInterpolatedStringHandlerConversion)) { if (valOverInOrRefInterpolatedHandlerPreference == BetterResult.Left) { return BetterResult.Neither; } else { valOverInOrRefInterpolatedHandlerPreference = BetterResult.Right; } } } } return valOverInOrRefInterpolatedHandlerPreference; static bool isAcceptableRefMismatch(RefKind refKind, bool isInterpolatedStringHandlerConversion) => refKind switch { RefKind.In => true, RefKind.Ref when isInterpolatedStringHandlerConversion => true, _ => false }; } #nullable disable private static void GetParameterCounts<TMember>(MemberResolutionResult<TMember> m, ArrayBuilder<BoundExpression> arguments, out int declaredParameterCount, out int parametersUsedIncludingExpansionAndOptional) where TMember : Symbol { declaredParameterCount = m.Member.GetParameterCount(); if (m.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { if (arguments.Count < declaredParameterCount) { ImmutableArray<int> argsToParamsOpt = m.Result.ArgsToParamsOpt; if (argsToParamsOpt.IsDefaultOrEmpty || !argsToParamsOpt.Contains(declaredParameterCount - 1)) { // params parameter isn't used (see ExpressionBinder::TryGetExpandedParams in the native compiler) parametersUsedIncludingExpansionAndOptional = declaredParameterCount - 1; } else { // params parameter is used by a named argument parametersUsedIncludingExpansionAndOptional = declaredParameterCount; } } else { parametersUsedIncludingExpansionAndOptional = arguments.Count; } } else { parametersUsedIncludingExpansionAndOptional = declaredParameterCount; } } private static BetterResult MoreSpecificType(ArrayBuilder<TypeSymbol> t1, ArrayBuilder<TypeSymbol> t2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(t1.Count == t2.Count); // For t1 to be more specific than t2, it has to be not less specific in every member, // and more specific in at least one. var result = BetterResult.Neither; for (int i = 0; i < t1.Count; ++i) { var r = MoreSpecificType(t1[i], t2[i], ref useSiteInfo); if (r == BetterResult.Neither) { // We learned nothing. Do nothing. } else if (result == BetterResult.Neither) { // We have found the first more specific type. See if // all the rest on this side are not less specific. result = r; } else if (result != r) { // We have more specific types on both left and right, so we // cannot succeed in picking a better type list. Bail out now. return BetterResult.Neither; } } return result; } private static BetterResult MoreSpecificType(TypeSymbol t1, TypeSymbol t2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Spec 7.5.3.2: // - A type parameter is less specific than a non-type parameter. var t1IsTypeParameter = t1.IsTypeParameter(); var t2IsTypeParameter = t2.IsTypeParameter(); if (t1IsTypeParameter && !t2IsTypeParameter) { return BetterResult.Right; } if (!t1IsTypeParameter && t2IsTypeParameter) { return BetterResult.Left; } if (t1IsTypeParameter && t2IsTypeParameter) { return BetterResult.Neither; } // Spec: // - An array type is more specific than another array type (with the same number of dimensions) // if the element type of the first is more specific than the element type of the second. if (t1.IsArray()) { var arr1 = (ArrayTypeSymbol)t1; var arr2 = (ArrayTypeSymbol)t2; // We should not have gotten here unless there were identity conversions // between the two types. Debug.Assert(arr1.HasSameShapeAs(arr2)); return MoreSpecificType(arr1.ElementType, arr2.ElementType, ref useSiteInfo); } // SPEC EXTENSION: We apply the same rule to pointer types. if (t1.TypeKind == TypeKind.Pointer) { var p1 = (PointerTypeSymbol)t1; var p2 = (PointerTypeSymbol)t2; return MoreSpecificType(p1.PointedAtType, p2.PointedAtType, ref useSiteInfo); } if (t1.IsDynamic() || t2.IsDynamic()) { Debug.Assert(t1.IsDynamic() && t2.IsDynamic() || t1.IsDynamic() && t2.SpecialType == SpecialType.System_Object || t2.IsDynamic() && t1.SpecialType == SpecialType.System_Object); return BetterResult.Neither; } // Spec: // - A constructed type is more specific than another // constructed type (with the same number of type arguments) if at least one type // argument is more specific and no type argument is less specific than the // corresponding type argument in the other. var n1 = t1 as NamedTypeSymbol; var n2 = t2 as NamedTypeSymbol; Debug.Assert(((object)n1 == null) == ((object)n2 == null)); if ((object)n1 == null) { return BetterResult.Neither; } // We should not have gotten here unless there were identity conversions between the // two types, or they are different Task-likes. Ideally we'd assert that the two types (or // Task equivalents) have the same OriginalDefinition but we don't have a Compilation // here for NormalizeTaskTypes. var allTypeArgs1 = ArrayBuilder<TypeSymbol>.GetInstance(); var allTypeArgs2 = ArrayBuilder<TypeSymbol>.GetInstance(); n1.GetAllTypeArguments(allTypeArgs1, ref useSiteInfo); n2.GetAllTypeArguments(allTypeArgs2, ref useSiteInfo); var result = MoreSpecificType(allTypeArgs1, allTypeArgs2, ref useSiteInfo); allTypeArgs1.Free(); allTypeArgs2.Free(); return result; } // Determine whether t1 or t2 is a better conversion target from node. private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, TypeSymbol t2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { bool ignore; return BetterConversionFromExpression( node, t1, Conversions.ClassifyImplicitConversionFromExpression(node, t1, ref useSiteInfo), t2, Conversions.ClassifyImplicitConversionFromExpression(node, t2, ref useSiteInfo), ref useSiteInfo, out ignore); } // Determine whether t1 or t2 is a better conversion target from node, possibly considering parameter ref kinds. private BetterResult BetterConversionFromExpression( BoundExpression node, TypeSymbol t1, Conversion conv1, RefKind refKind1, TypeSymbol t2, Conversion conv2, RefKind refKind2, bool considerRefKinds, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool okToDowngradeToNeither) { okToDowngradeToNeither = false; if (considerRefKinds) { // We may need to consider the ref kinds of the parameters while determining the better conversion from the given expression to the respective parameter types. // This is needed for the omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method within a COM imported type. // We can reach here only if we had at least one ref omitted argument for the given call, which must be a call to a method within a COM imported type. // Algorithm for determining the better conversion from expression when ref kinds need to be considered is NOT provided in the C# language specification, // see section 7.5.3.3 'Better Conversion From Expression'. // We match native compiler's behavior for determining the better conversion as follows: // 1) If one of the contending parameters is a 'ref' parameter, say p1, and other is a non-ref parameter, say p2, // then p2 is a better result if the argument has an identity conversion to p2's type. Otherwise, neither result is better. // 2) Otherwise, if both the contending parameters are 'ref' parameters, neither result is better. // 3) Otherwise, we use the algorithm in 7.5.3.3 for determining the better conversion without considering ref kinds. // NOTE: Native compiler does not explicitly implement the above algorithm, but gets it by default. This is due to the fact that the RefKind of a parameter // NOTE: gets considered while classifying conversions between parameter types when computing better conversion target in the native compiler. // NOTE: Roslyn correctly follows the specification and ref kinds are not considered while classifying conversions between types, see method BetterConversionTarget. Debug.Assert(refKind1 == RefKind.None || refKind1 == RefKind.Ref); Debug.Assert(refKind2 == RefKind.None || refKind2 == RefKind.Ref); if (refKind1 != refKind2) { if (refKind1 == RefKind.None) { return conv1.Kind == ConversionKind.Identity ? BetterResult.Left : BetterResult.Neither; } else { return conv2.Kind == ConversionKind.Identity ? BetterResult.Right : BetterResult.Neither; } } else if (refKind1 == RefKind.Ref) { return BetterResult.Neither; } } return BetterConversionFromExpression(node, t1, conv1, t2, conv2, ref useSiteInfo, out okToDowngradeToNeither); } // Determine whether t1 or t2 is a better conversion target from node. private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, Conversion conv1, TypeSymbol t2, Conversion conv2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool okToDowngradeToNeither) { okToDowngradeToNeither = false; if (Conversions.HasIdentityConversion(t1, t2)) { // Both parameters have the same type. return BetterResult.Neither; } var lambdaOpt = node as UnboundLambda; var nodeKind = node.Kind; if (nodeKind == BoundKind.OutVariablePendingInference || nodeKind == BoundKind.OutDeconstructVarPendingInference || (nodeKind == BoundKind.DiscardExpression && !node.HasExpressionType())) { // Neither conversion from expression is better when the argument is an implicitly-typed out variable declaration. okToDowngradeToNeither = false; return BetterResult.Neither; } // C# 10 added interpolated string handler conversions, with the following rule: // Given an implicit conversion C1 that converts from an expression E to a type T1, // and an implicit conversion C2 that converts from an expression E to a type T2, // C1 is a better conversion than C2 if E is a non-constant interpolated string expression, C1 // is an interpolated string handler conversion, and C2 is not an interpolated string // handler conversion. // We deviate from our usual policy around language version not changing binding behavior here // because this will cause existing code that chooses one overload to instead choose an overload // that will immediately cause an error. True, the user does need to update their target framework // or a library to a version that takes advantage of the feature, but we made this pragmatic // choice after we received customer reports of problems in the space. // https://github.com/dotnet/roslyn/issues/55345 if (_binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && node is BoundUnconvertedInterpolatedString { ConstantValueOpt: null } or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true, ConstantValue: null }) { switch ((conv1.Kind, conv2.Kind)) { case (ConversionKind.InterpolatedStringHandler, ConversionKind.InterpolatedStringHandler): return BetterResult.Neither; case (ConversionKind.InterpolatedStringHandler, _): return BetterResult.Left; case (_, ConversionKind.InterpolatedStringHandler): return BetterResult.Right; } } switch ((conv1.Kind, conv2.Kind)) { case (ConversionKind.FunctionType, ConversionKind.FunctionType): break; case (_, ConversionKind.FunctionType): return BetterResult.Left; case (ConversionKind.FunctionType, _): return BetterResult.Right; } // Given an implicit conversion C1 that converts from an expression E to a type T1, // and an implicit conversion C2 that converts from an expression E to a type T2, // C1 is a better conversion than C2 if E does not exactly match T2 and one of the following holds: bool t1MatchesExactly = ExpressionMatchExactly(node, t1, ref useSiteInfo); bool t2MatchesExactly = ExpressionMatchExactly(node, t2, ref useSiteInfo); if (t1MatchesExactly) { if (!t2MatchesExactly) { // - E exactly matches T1 okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Left, lambdaOpt, t1, t2, ref useSiteInfo, false); return BetterResult.Left; } } else if (t2MatchesExactly) { okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Right, lambdaOpt, t1, t2, ref useSiteInfo, false); return BetterResult.Right; } // - C1 is not a conditional expression conversion and C2 is a conditional expression conversion if (!conv1.IsConditionalExpression && conv2.IsConditionalExpression) return BetterResult.Left; if (!conv2.IsConditionalExpression && conv1.IsConditionalExpression) return BetterResult.Right; // - T1 is a better conversion target than T2 and either C1 and C2 are both conditional expression // conversions or neither is a conditional expression conversion. return BetterConversionTarget(node, t1, conv1, t2, conv2, ref useSiteInfo, out okToDowngradeToNeither); } private bool ExpressionMatchExactly(BoundExpression node, TypeSymbol t, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Given an expression E and a type T, E exactly matches T if one of the following holds: // - E has a type S, and an identity conversion exists from S to T if ((object)node.Type != null && Conversions.HasIdentityConversion(node.Type, t)) { return true; } if (node.Kind == BoundKind.TupleLiteral) { // Recurse into tuple constituent arguments. // Even if the tuple literal has a natural type and conversion // from that type is not identity, we still have to do this // because we might be converting to a tuple type backed by // different definition of ValueTuple type. return ExpressionMatchExactly((BoundTupleLiteral)node, t, ref useSiteInfo); } // - E is an anonymous function, T is either a delegate type D or an expression tree // type Expression<D>, D has a return type Y, and one of the following holds: NamedTypeSymbol d; MethodSymbol invoke; TypeSymbol y; if (node.Kind == BoundKind.UnboundLambda && (object)(d = t.GetDelegateType()) != null && (object)(invoke = d.DelegateInvokeMethod) != null && !(y = invoke.ReturnType).IsVoidType()) { BoundLambda lambda = ((UnboundLambda)node).BindForReturnTypeInference(d); // - an inferred return type X exists for E in the context of the parameter list of D(§7.5.2.12), and an identity conversion exists from X to Y var x = lambda.GetInferredReturnType(ref useSiteInfo); if (x.HasType && Conversions.HasIdentityConversion(x.Type, y)) { return true; } if (lambda.Symbol.IsAsync) { // Dig through Task<...> for an async lambda. if (y.OriginalDefinition.IsGenericTaskType(Compilation)) { y = ((NamedTypeSymbol)y).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; } else { y = null; } } if ((object)y != null) { // - The body of E is an expression that exactly matches Y, or // has a return statement with expression and all return statements have expression that // exactly matches Y. // Handle trivial cases first switch (lambda.Body.Statements.Length) { case 0: break; case 1: if (lambda.Body.Statements[0].Kind == BoundKind.ReturnStatement) { var returnStmt = (BoundReturnStatement)lambda.Body.Statements[0]; if (returnStmt.ExpressionOpt != null && ExpressionMatchExactly(returnStmt.ExpressionOpt, y, ref useSiteInfo)) { return true; } } else { goto default; } break; default: var returnStatements = ArrayBuilder<BoundReturnStatement>.GetInstance(); var walker = new ReturnStatements(returnStatements); walker.Visit(lambda.Body); bool result = false; foreach (BoundReturnStatement r in returnStatements) { if (r.ExpressionOpt == null || !ExpressionMatchExactly(r.ExpressionOpt, y, ref useSiteInfo)) { result = false; break; } else { result = true; } } returnStatements.Free(); if (result) { return true; } break; } } } return false; } // check every argument of a tuple vs corresponding type in destination tuple type private bool ExpressionMatchExactly(BoundTupleLiteral tupleSource, TypeSymbol targetType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (targetType.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types and either is a named type return false; } var destination = (NamedTypeSymbol)targetType; var sourceArguments = tupleSource.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { if (!ExpressionMatchExactly(sourceArguments[i], destTypes[i].Type, ref useSiteInfo)) { return false; } } return true; } private class ReturnStatements : BoundTreeWalker { private readonly ArrayBuilder<BoundReturnStatement> _returns; public ReturnStatements(ArrayBuilder<BoundReturnStatement> returns) { _returns = returns; } public override BoundNode Visit(BoundNode node) { if (!(node is BoundExpression)) { return base.Visit(node); } return null; } protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { // Do not recurse into nested local functions; we don't want their returns. return null; } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { _returns.Add(node); return null; } } private const int BetterConversionTargetRecursionLimit = 100; private BetterResult BetterConversionTarget( TypeSymbol type1, TypeSymbol type2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { bool okToDowngradeToNeither; return BetterConversionTargetCore(null, type1, default(Conversion), type2, default(Conversion), ref useSiteInfo, out okToDowngradeToNeither, BetterConversionTargetRecursionLimit); } private BetterResult BetterConversionTargetCore( TypeSymbol type1, TypeSymbol type2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, int betterConversionTargetRecursionLimit) { if (betterConversionTargetRecursionLimit < 0) { return BetterResult.Neither; } bool okToDowngradeToNeither; return BetterConversionTargetCore(null, type1, default(Conversion), type2, default(Conversion), ref useSiteInfo, out okToDowngradeToNeither, betterConversionTargetRecursionLimit - 1); } private BetterResult BetterConversionTarget( BoundExpression node, TypeSymbol type1, Conversion conv1, TypeSymbol type2, Conversion conv2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool okToDowngradeToNeither) { return BetterConversionTargetCore(node, type1, conv1, type2, conv2, ref useSiteInfo, out okToDowngradeToNeither, BetterConversionTargetRecursionLimit); } private BetterResult BetterConversionTargetCore( BoundExpression node, TypeSymbol type1, Conversion conv1, TypeSymbol type2, Conversion conv2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool okToDowngradeToNeither, int betterConversionTargetRecursionLimit) { okToDowngradeToNeither = false; if (Conversions.HasIdentityConversion(type1, type2)) { // Both types are the same type. return BetterResult.Neither; } // Given two different types T1 and T2, T1 is a better conversion target than T2 if no implicit conversion from T2 to T1 exists, // and at least one of the following holds: bool type1ToType2 = Conversions.ClassifyImplicitConversionFromType(type1, type2, ref useSiteInfo).IsImplicit; bool type2ToType1 = Conversions.ClassifyImplicitConversionFromType(type2, type1, ref useSiteInfo).IsImplicit; UnboundLambda lambdaOpt = node as UnboundLambda; if (type1ToType2) { if (type2ToType1) { // An implicit conversion both ways. return BetterResult.Neither; } // - An implicit conversion from T1 to T2 exists okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Left, lambdaOpt, type1, type2, ref useSiteInfo, true); return BetterResult.Left; } else if (type2ToType1) { // - An implicit conversion from T1 to T2 exists okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Right, lambdaOpt, type1, type2, ref useSiteInfo, true); return BetterResult.Right; } bool type1IsGenericTask = type1.OriginalDefinition.IsGenericTaskType(Compilation); bool type2IsGenericTask = type2.OriginalDefinition.IsGenericTaskType(Compilation); if (type1IsGenericTask) { if (type2IsGenericTask) { // - T1 is Task<S1>, T2 is Task<S2>, and S1 is a better conversion target than S2 return BetterConversionTargetCore(((NamedTypeSymbol)type1).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ((NamedTypeSymbol)type2).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, betterConversionTargetRecursionLimit); } // A shortcut, Task<T> type cannot satisfy other rules. return BetterResult.Neither; } else if (type2IsGenericTask) { // A shortcut, Task<T> type cannot satisfy other rules. return BetterResult.Neither; } NamedTypeSymbol d1; if ((object)(d1 = type1.GetDelegateType()) != null) { NamedTypeSymbol d2; if ((object)(d2 = type2.GetDelegateType()) != null) { // - T1 is either a delegate type D1 or an expression tree type Expression<D1>, // T2 is either a delegate type D2 or an expression tree type Expression<D2>, // D1 has a return type S1 and one of the following holds: MethodSymbol invoke1 = d1.DelegateInvokeMethod; MethodSymbol invoke2 = d2.DelegateInvokeMethod; if ((object)invoke1 != null && (object)invoke2 != null) { TypeSymbol r1 = invoke1.ReturnType; TypeSymbol r2 = invoke2.ReturnType; BetterResult delegateResult = BetterResult.Neither; if (!r1.IsVoidType()) { if (r2.IsVoidType()) { // - D2 is void returning delegateResult = BetterResult.Left; } } else if (!r2.IsVoidType()) { // - D2 is void returning delegateResult = BetterResult.Right; } if (delegateResult == BetterResult.Neither) { // - D2 has a return type S2, and S1 is a better conversion target than S2 delegateResult = BetterConversionTargetCore(r1, r2, ref useSiteInfo, betterConversionTargetRecursionLimit); } // Downgrade result to Neither if conversion used by the winner isn't actually valid method group conversion. // This is necessary to preserve compatibility, otherwise we might dismiss "worse", but truly applicable candidate // based on a "better", but, in reality, erroneous one. if (node?.Kind == BoundKind.MethodGroup) { var group = (BoundMethodGroup)node; if (delegateResult == BetterResult.Left) { if (IsMethodGroupConversionIncompatibleWithDelegate(group, d1, conv1)) { return BetterResult.Neither; } } else if (delegateResult == BetterResult.Right && IsMethodGroupConversionIncompatibleWithDelegate(group, d2, conv2)) { return BetterResult.Neither; } } return delegateResult; } } // A shortcut, a delegate or an expression tree cannot satisfy other rules. return BetterResult.Neither; } else if ((object)type2.GetDelegateType() != null) { // A shortcut, a delegate or an expression tree cannot satisfy other rules. return BetterResult.Neither; } // -T1 is a signed integral type and T2 is an unsigned integral type.Specifically: // - T1 is sbyte and T2 is byte, ushort, uint, or ulong // - T1 is short and T2 is ushort, uint, or ulong // - T1 is int and T2 is uint, or ulong // - T1 is long and T2 is ulong if (IsSignedIntegralType(type1)) { if (IsUnsignedIntegralType(type2)) { return BetterResult.Left; } } else if (IsUnsignedIntegralType(type1) && IsSignedIntegralType(type2)) { return BetterResult.Right; } return BetterResult.Neither; } private bool IsMethodGroupConversionIncompatibleWithDelegate(BoundMethodGroup node, NamedTypeSymbol delegateType, Conversion conv) { if (conv.IsMethodGroup) { bool result = !_binder.MethodIsCompatibleWithDelegateOrFunctionPointer(node.ReceiverOpt, conv.IsExtensionMethod, conv.Method, delegateType, Location.None, BindingDiagnosticBag.Discarded); return result; } return false; } private bool CanDowngradeConversionFromLambdaToNeither(BetterResult currentResult, UnboundLambda lambda, TypeSymbol type1, TypeSymbol type2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool fromTypeAnalysis) { // DELIBERATE SPEC VIOLATION: See bug 11961. // The native compiler uses one algorithm for determining betterness of lambdas and another one // for everything else. This is wrong; the correct behavior is to do the type analysis of // the parameter types first, and then if necessary, do the lambda analysis. Native compiler // skips analysis of the parameter types when they are delegate types with identical parameter // lists and the corresponding argument is a lambda. // There is a real-world code that breaks if we follow the specification, so we will try to fall // back to the original behavior to avoid an ambiguity that wasn't an ambiguity before. NamedTypeSymbol d1; if ((object)(d1 = type1.GetDelegateType()) != null) { NamedTypeSymbol d2; if ((object)(d2 = type2.GetDelegateType()) != null) { MethodSymbol invoke1 = d1.DelegateInvokeMethod; MethodSymbol invoke2 = d2.DelegateInvokeMethod; if ((object)invoke1 != null && (object)invoke2 != null) { if (!IdenticalParameters(invoke1.Parameters, invoke2.Parameters)) { return true; } TypeSymbol r1 = invoke1.ReturnType; TypeSymbol r2 = invoke2.ReturnType; #if DEBUG if (fromTypeAnalysis) { Debug.Assert((r1.IsVoidType()) == (r2.IsVoidType())); // Since we are dealing with variance delegate conversion and delegates have identical parameter // lists, return types must be different and neither can be void. Debug.Assert(!r1.IsVoidType()); Debug.Assert(!r2.IsVoidType()); Debug.Assert(!Conversions.HasIdentityConversion(r1, r2)); } #endif if (r1.IsVoidType()) { if (r2.IsVoidType()) { return true; } Debug.Assert(currentResult == BetterResult.Right); return false; } else if (r2.IsVoidType()) { Debug.Assert(currentResult == BetterResult.Left); return false; } if (Conversions.HasIdentityConversion(r1, r2)) { return true; } var x = lambda.InferReturnType(Conversions, d1, ref useSiteInfo); if (!x.HasType) { return true; } #if DEBUG if (fromTypeAnalysis) { // Since we are dealing with variance delegate conversion and delegates have identical parameter // lists, return types must be implicitly convertible in the same direction. // Or we might be dealing with error return types and we may have one error delegate matching exactly // while another not being an error and not convertible. Debug.Assert( r1.IsErrorType() || r2.IsErrorType() || currentResult == BetterConversionTarget(r1, r2, ref useSiteInfo)); } #endif } } } return false; } private static bool IdenticalParameters(ImmutableArray<ParameterSymbol> p1, ImmutableArray<ParameterSymbol> p2) { if (p1.IsDefault || p2.IsDefault) { // This only happens in error scenarios. return false; } if (p1.Length != p2.Length) { return false; } for (int i = 0; i < p1.Length; ++i) { var param1 = p1[i]; var param2 = p2[i]; if (param1.RefKind != param2.RefKind) { return false; } if (!Conversions.HasIdentityConversion(param1.Type, param2.Type)) { return false; } } return true; } private static bool IsSignedIntegralType(TypeSymbol type) { if ((object)type != null && type.IsNullableType()) { type = type.GetNullableUnderlyingType(); } switch (type.GetSpecialTypeSafe()) { case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_IntPtr: return true; default: return false; } } private static bool IsUnsignedIntegralType(TypeSymbol type) { if ((object)type != null && type.IsNullableType()) { type = type.GetNullableUnderlyingType(); } switch (type.GetSpecialTypeSafe()) { case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_UIntPtr: return true; default: return false; } } internal static void GetEffectiveParameterTypes( MethodSymbol method, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, bool expanded, out ImmutableArray<TypeWithAnnotations> parameterTypes, out ImmutableArray<RefKind> parameterRefKinds) { bool hasAnyRefOmittedArgument; EffectiveParameters effectiveParameters = expanded ? GetEffectiveParametersInExpandedForm(method, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, binder, out hasAnyRefOmittedArgument) : GetEffectiveParametersInNormalForm(method, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, binder, out hasAnyRefOmittedArgument); parameterTypes = effectiveParameters.ParameterTypes; parameterRefKinds = effectiveParameters.ParameterRefKinds; } private struct EffectiveParameters { internal readonly ImmutableArray<TypeWithAnnotations> ParameterTypes; internal readonly ImmutableArray<RefKind> ParameterRefKinds; internal EffectiveParameters(ImmutableArray<TypeWithAnnotations> types, ImmutableArray<RefKind> refKinds) { ParameterTypes = types; ParameterRefKinds = refKinds; } } private EffectiveParameters GetEffectiveParametersInNormalForm<TMember>( TMember member, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments) where TMember : Symbol { bool discarded; return GetEffectiveParametersInNormalForm(member, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, hasAnyRefOmittedArgument: out discarded); } private static EffectiveParameters GetEffectiveParametersInNormalForm<TMember>( TMember member, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, out bool hasAnyRefOmittedArgument) where TMember : Symbol { Debug.Assert(argumentRefKinds != null); hasAnyRefOmittedArgument = false; ImmutableArray<ParameterSymbol> parameters = member.GetParameters(); // We simulate an extra parameter for vararg methods int parameterCount = member.GetParameterCount() + (member.GetIsVararg() ? 1 : 0); if (argumentCount == parameterCount && argToParamMap.IsDefaultOrEmpty) { ImmutableArray<RefKind> parameterRefKinds = member.GetParameterRefKinds(); if (parameterRefKinds.IsDefaultOrEmpty) { return new EffectiveParameters(member.GetParameterTypes(), parameterRefKinds); } } var types = ArrayBuilder<TypeWithAnnotations>.GetInstance(); ArrayBuilder<RefKind> refs = null; bool hasAnyRefArg = argumentRefKinds.Any(); for (int arg = 0; arg < argumentCount; ++arg) { int parm = argToParamMap.IsDefault ? arg : argToParamMap[arg]; // If this is the __arglist parameter, or an extra argument in error situations, just skip it. if (parm >= parameters.Length) { continue; } var parameter = parameters[parm]; types.Add(parameter.TypeWithAnnotations); RefKind argRefKind = hasAnyRefArg ? argumentRefKinds[arg] : RefKind.None; RefKind paramRefKind = GetEffectiveParameterRefKind(parameter, argRefKind, isMethodGroupConversion, allowRefOmittedArguments, binder, ref hasAnyRefOmittedArgument); if (refs == null) { if (paramRefKind != RefKind.None) { refs = ArrayBuilder<RefKind>.GetInstance(arg, RefKind.None); refs.Add(paramRefKind); } } else { refs.Add(paramRefKind); } } var refKinds = refs != null ? refs.ToImmutableAndFree() : default(ImmutableArray<RefKind>); return new EffectiveParameters(types.ToImmutableAndFree(), refKinds); } private static RefKind GetEffectiveParameterRefKind( ParameterSymbol parameter, RefKind argRefKind, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, ref bool hasAnyRefOmittedArgument) { var paramRefKind = parameter.RefKind; // 'None' argument is allowed to match 'In' parameter and should behave like 'None' for the purpose of overload resolution // unless this is a method group conversion where 'In' must match 'In' if (!isMethodGroupConversion && argRefKind == RefKind.None && paramRefKind == RefKind.In) { return RefKind.None; } // Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method/property on an instance of a COM imported type. // We must ignore the 'ref' on the parameter while determining the applicability of argument for the given method call. // During argument rewriting, we will replace the argument value with a temporary local and pass that local by reference. if (allowRefOmittedArguments && paramRefKind == RefKind.Ref && argRefKind == RefKind.None && !binder.InAttributeArgument) { hasAnyRefOmittedArgument = true; return RefKind.None; } return paramRefKind; } private EffectiveParameters GetEffectiveParametersInExpandedForm<TMember>( TMember member, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments) where TMember : Symbol { bool discarded; return GetEffectiveParametersInExpandedForm(member, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, hasAnyRefOmittedArgument: out discarded); } private static EffectiveParameters GetEffectiveParametersInExpandedForm<TMember>( TMember member, int argumentCount, ImmutableArray<int> argToParamMap, ArrayBuilder<RefKind> argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, out bool hasAnyRefOmittedArgument) where TMember : Symbol { Debug.Assert(argumentRefKinds != null); var types = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var refs = ArrayBuilder<RefKind>.GetInstance(); bool anyRef = false; var parameters = member.GetParameters(); bool hasAnyRefArg = argumentRefKinds.Any(); hasAnyRefOmittedArgument = false; for (int arg = 0; arg < argumentCount; ++arg) { var parm = argToParamMap.IsDefault ? arg : argToParamMap[arg]; var parameter = parameters[parm]; var type = parameter.TypeWithAnnotations; types.Add(parm == parameters.Length - 1 ? ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations : type); var argRefKind = hasAnyRefArg ? argumentRefKinds[arg] : RefKind.None; var paramRefKind = GetEffectiveParameterRefKind(parameter, argRefKind, isMethodGroupConversion, allowRefOmittedArguments, binder, ref hasAnyRefOmittedArgument); refs.Add(paramRefKind); if (paramRefKind != RefKind.None) { anyRef = true; } } var refKinds = anyRef ? refs.ToImmutable() : default(ImmutableArray<RefKind>); refs.Free(); return new EffectiveParameters(types.ToImmutableAndFree(), refKinds); } private MemberResolutionResult<TMember> IsMemberApplicableInNormalForm<TMember>( TMember member, // method or property TMember leastOverriddenMember, // method or property ArrayBuilder<TypeWithAnnotations> typeArguments, AnalyzedArguments arguments, bool isMethodGroupConversion, bool allowRefOmittedArguments, bool inferWithDynamic, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { // AnalyzeArguments matches arguments to parameter names and positions. // For that purpose we use the most derived member. var argumentAnalysis = AnalyzeArguments(member, arguments, isMethodGroupConversion, expanded: false); if (!argumentAnalysis.IsValid) { switch (argumentAnalysis.Kind) { case ArgumentAnalysisResultKind.RequiredParameterMissing: case ArgumentAnalysisResultKind.NoCorrespondingParameter: case ArgumentAnalysisResultKind.DuplicateNamedArgument: if (!completeResults) goto default; // When we are producing more complete results, and we have the wrong number of arguments, we push on // through type inference so that lambda arguments can be bound to their delegate-typed parameters, // thus improving the API and intellisense experience. break; default: return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis)); } } // Check after argument analysis, but before more complicated type inference and argument type validation. // NOTE: The diagnostic may not be reported (e.g. if the member is later removed as less-derived). if (member.HasUseSiteError) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UseSiteError()); } bool hasAnyRefOmittedArgument; // To determine parameter types we use the originalMember. EffectiveParameters originalEffectiveParameters = GetEffectiveParametersInNormalForm( GetConstructedFrom(leastOverriddenMember), arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, out hasAnyRefOmittedArgument); Debug.Assert(!hasAnyRefOmittedArgument || allowRefOmittedArguments); // To determine parameter types we use the originalMember. EffectiveParameters constructedEffectiveParameters = GetEffectiveParametersInNormalForm( leastOverriddenMember, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion, allowRefOmittedArguments); // The member passed to the following call is returned in the result (possibly a constructed version of it). // The applicability is checked based on effective parameters passed in. var applicableResult = IsApplicable( member, leastOverriddenMember, typeArguments, arguments, originalEffectiveParameters, constructedEffectiveParameters, argumentAnalysis.ArgsToParamsOpt, hasAnyRefOmittedArgument: hasAnyRefOmittedArgument, inferWithDynamic: inferWithDynamic, completeResults: completeResults, useSiteInfo: ref useSiteInfo); // If we were producing complete results and had missing arguments, we pushed on in order to call IsApplicable for // type inference and lambda binding. In that case we still need to return the argument mismatch failure here. if (completeResults && !argumentAnalysis.IsValid) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis)); } return applicableResult; } private MemberResolutionResult<TMember> IsMemberApplicableInExpandedForm<TMember>( TMember member, // method or property TMember leastOverriddenMember, // method or property ArrayBuilder<TypeWithAnnotations> typeArguments, AnalyzedArguments arguments, bool allowRefOmittedArguments, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { // AnalyzeArguments matches arguments to parameter names and positions. // For that purpose we use the most derived member. var argumentAnalysis = AnalyzeArguments(member, arguments, isMethodGroupConversion: false, expanded: true); if (!argumentAnalysis.IsValid) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis)); } // Check after argument analysis, but before more complicated type inference and argument type validation. // NOTE: The diagnostic may not be reported (e.g. if the member is later removed as less-derived). if (member.HasUseSiteError) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UseSiteError()); } bool hasAnyRefOmittedArgument; // To determine parameter types we use the least derived member. EffectiveParameters originalEffectiveParameters = GetEffectiveParametersInExpandedForm( GetConstructedFrom(leastOverriddenMember), arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments, _binder, out hasAnyRefOmittedArgument); Debug.Assert(!hasAnyRefOmittedArgument || allowRefOmittedArguments); // To determine parameter types we use the least derived member. EffectiveParameters constructedEffectiveParameters = GetEffectiveParametersInExpandedForm( leastOverriddenMember, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments); // The member passed to the following call is returned in the result (possibly a constructed version of it). // The applicability is checked based on effective parameters passed in. var result = IsApplicable( member, leastOverriddenMember, typeArguments, arguments, originalEffectiveParameters, constructedEffectiveParameters, argumentAnalysis.ArgsToParamsOpt, hasAnyRefOmittedArgument: hasAnyRefOmittedArgument, inferWithDynamic: false, completeResults: completeResults, useSiteInfo: ref useSiteInfo); return result.Result.IsValid ? new MemberResolutionResult<TMember>( result.Member, result.LeastOverriddenMember, MemberAnalysisResult.ExpandedForm(result.Result.ArgsToParamsOpt, result.Result.ConversionsOpt, hasAnyRefOmittedArgument)) : result; } private MemberResolutionResult<TMember> IsApplicable<TMember>( TMember member, // method or property TMember leastOverriddenMember, // method or property ArrayBuilder<TypeWithAnnotations> typeArgumentsBuilder, AnalyzedArguments arguments, EffectiveParameters originalEffectiveParameters, EffectiveParameters constructedEffectiveParameters, ImmutableArray<int> argsToParamsMap, bool hasAnyRefOmittedArgument, bool inferWithDynamic, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) where TMember : Symbol { bool ignoreOpenTypes; MethodSymbol method; EffectiveParameters effectiveParameters; bool hasTypeArgumentsInferredFromFunctionType = false; if (member.Kind == SymbolKind.Method && (method = (MethodSymbol)(Symbol)member).Arity > 0) { if (typeArgumentsBuilder.Count == 0 && arguments.HasDynamicArgument && !inferWithDynamic) { // Spec 7.5.4: Compile-time checking of dynamic overload resolution: // * First, if F is a generic method and type arguments were provided, // then those are substituted for the type parameters in the parameter list. // However, if type arguments were not provided, no such substitution happens. // * Then, any parameter whose type contains a an unsubstituted type parameter of F // is elided, along with the corresponding arguments(s). // We don't need to check constraints of types of the non-elided parameters since they // have no effect on applicability of this candidate. ignoreOpenTypes = true; effectiveParameters = constructedEffectiveParameters; } else { MethodSymbol leastOverriddenMethod = (MethodSymbol)(Symbol)leastOverriddenMember; ImmutableArray<TypeWithAnnotations> typeArguments; if (typeArgumentsBuilder.Count > 0) { // generic type arguments explicitly specified at call-site: typeArguments = typeArgumentsBuilder.ToImmutable(); } else { // infer generic type arguments: MemberAnalysisResult inferenceError; typeArguments = InferMethodTypeArguments(method, leastOverriddenMethod.ConstructedFrom.TypeParameters, arguments, originalEffectiveParameters, out hasTypeArgumentsInferredFromFunctionType, out inferenceError, ref useSiteInfo); if (typeArguments.IsDefault) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, inferenceError); } } member = (TMember)(Symbol)method.Construct(typeArguments); leastOverriddenMember = (TMember)(Symbol)leastOverriddenMethod.ConstructedFrom.Construct(typeArguments); // Spec (§7.6.5.1) // Once the (inferred) type arguments are substituted for the corresponding method type parameters, // all constructed types in the parameter list of F satisfy *their* constraints (§4.4.4), // and the parameter list of F is applicable with respect to A (§7.5.3.1). // // This rule is a bit complicated; let's take a look at an example. Suppose we have // class X<U> where U : struct {} // ... // void M<T>(T t, X<T> xt) where T : struct {} // void M(object o1, object o2) {} // // Suppose there is a call M("", null). Type inference infers that T is string. // M<string> is then not an applicable candidate *NOT* because string violates the // constraint on T. That is not checked until "final validation" (although when // feature 'ImprovedOverloadCandidates' is enabled in later language versions // it is checked on the candidate before overload resolution). Rather, the // method is not a candidate because string violates the constraint *on U*. // The constructed method has formal parameter type X<string>, which is not legal. // In the case given, the generic method is eliminated and the object version wins. // // Note also that the constraints need to be checked on *all* the formal parameter // types, not just the ones in the *effective parameter list*. If we had: // void M<T>(T t, X<T> xt = null) where T : struct {} // void M<T>(object o1, object o2 = null) where T : struct {} // and a call M("") then type inference still works out that T is string, and // the generic method still needs to be discarded, even though type inference // never saw the second formal parameter. var parameterTypes = leastOverriddenMember.GetParameterTypes(); for (int i = 0; i < parameterTypes.Length; i++) { if (!parameterTypes[i].Type.CheckAllConstraints(Compilation, Conversions)) { return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ConstructedParameterFailedConstraintsCheck(i)); } } // Types of constructed effective parameters might originate from a virtual/abstract method // that the current "method" overrides. If the virtual/abstract method is generic we constructed it // using the generic parameters of "method", so we can now substitute these type parameters // in the constructed effective parameters. var map = new TypeMap(method.TypeParameters, typeArguments, allowAlpha: true); effectiveParameters = new EffectiveParameters( map.SubstituteTypes(constructedEffectiveParameters.ParameterTypes), constructedEffectiveParameters.ParameterRefKinds); ignoreOpenTypes = false; } } else { effectiveParameters = constructedEffectiveParameters; ignoreOpenTypes = false; } var applicableResult = IsApplicable( member, effectiveParameters, arguments, argsToParamsMap, isVararg: member.GetIsVararg(), hasAnyRefOmittedArgument: hasAnyRefOmittedArgument, ignoreOpenTypes: ignoreOpenTypes, completeResults: completeResults, useSiteInfo: ref useSiteInfo); return new MemberResolutionResult<TMember>(member, leastOverriddenMember, applicableResult, hasTypeArgumentsInferredFromFunctionType); } private ImmutableArray<TypeWithAnnotations> InferMethodTypeArguments( MethodSymbol method, ImmutableArray<TypeParameterSymbol> originalTypeParameters, AnalyzedArguments arguments, EffectiveParameters originalEffectiveParameters, out bool hasTypeArgumentsInferredFromFunctionType, out MemberAnalysisResult error, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var args = arguments.Arguments.ToImmutable(); // The reason why we pass the type parameters and formal parameter types // from the original definition, not the method as it exists as a member of // a possibly constructed generic type, is exceedingly subtle. See the comments // in "Infer" for details. var inferenceResult = MethodTypeInferrer.Infer( _binder, _binder.Conversions, originalTypeParameters, method.ContainingType, originalEffectiveParameters.ParameterTypes, originalEffectiveParameters.ParameterRefKinds, args, ref useSiteInfo); if (inferenceResult.Success) { hasTypeArgumentsInferredFromFunctionType = inferenceResult.HasTypeArgumentInferredFromFunctionType; error = default(MemberAnalysisResult); return inferenceResult.InferredTypeArguments; } if (arguments.IsExtensionMethodInvocation) { var inferredFromFirstArgument = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument( _binder.Compilation, _binder.Conversions, method, args, useSiteInfo: ref useSiteInfo); if (inferredFromFirstArgument.IsDefault) { hasTypeArgumentsInferredFromFunctionType = false; error = MemberAnalysisResult.TypeInferenceExtensionInstanceArgumentFailed(); return default(ImmutableArray<TypeWithAnnotations>); } } hasTypeArgumentsInferredFromFunctionType = false; error = MemberAnalysisResult.TypeInferenceFailed(); return default(ImmutableArray<TypeWithAnnotations>); } private MemberAnalysisResult IsApplicable( Symbol candidate, // method or property EffectiveParameters parameters, AnalyzedArguments arguments, ImmutableArray<int> argsToParameters, bool isVararg, bool hasAnyRefOmittedArgument, bool ignoreOpenTypes, bool completeResults, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // The effective parameters are in the right order with respect to the arguments. // // The difference between "parameters" and "original parameters" is as follows. Suppose // we have class C<V> { static void M<T, U>(T t, U u, V v) { C<T>.M(1, t, t); } } // In the call, the "original parameters" are (T, U, V). The "constructed parameters", // not passed in here, are (T, U, T) because T is substituted for V; type inference then // infers that T is int and U is T. The "parameters" are therefore (int, T, T). // // We add a "virtual parameter" for the __arglist. int paramCount = parameters.ParameterTypes.Length + (isVararg ? 1 : 0); if (arguments.Arguments.Count < paramCount) { // For improved error recovery, we perform type inference even when the argument // list is of the wrong length. The caller is expected to detect and handle that, // treating the method as inapplicable. paramCount = arguments.Arguments.Count; } // For each argument in A, the parameter passing mode of the argument (i.e., value, ref, or out) is // identical to the parameter passing mode of the corresponding parameter, and // * for a value parameter or a parameter array, an implicit conversion exists from the // argument to the type of the corresponding parameter, or // * for a ref or out parameter, the type of the argument is identical to the type of the corresponding // parameter. After all, a ref or out parameter is an alias for the argument passed. ArrayBuilder<Conversion> conversions = null; ArrayBuilder<int> badArguments = null; for (int argumentPosition = 0; argumentPosition < paramCount; argumentPosition++) { BoundExpression argument = arguments.Argument(argumentPosition); Conversion conversion; if (isVararg && argumentPosition == paramCount - 1) { // Only an __arglist() expression is convertible. if (argument.Kind == BoundKind.ArgListOperator) { conversion = Conversion.Identity; } else { badArguments = badArguments ?? ArrayBuilder<int>.GetInstance(); badArguments.Add(argumentPosition); conversion = Conversion.NoConversion; } } else { RefKind argumentRefKind = arguments.RefKind(argumentPosition); RefKind parameterRefKind = parameters.ParameterRefKinds.IsDefault ? RefKind.None : parameters.ParameterRefKinds[argumentPosition]; bool forExtensionMethodThisArg = arguments.IsExtensionMethodThisArgument(argumentPosition); if (forExtensionMethodThisArg) { Debug.Assert(argumentRefKind == RefKind.None); if (parameterRefKind == RefKind.Ref) { // For ref extension methods, we omit the "ref" modifier on the receiver arguments // Passing the parameter RefKind for finding the correct conversion. // For ref-readonly extension methods, argumentRefKind is always None. argumentRefKind = parameterRefKind; } } bool hasInterpolatedStringRefMismatch = false; if (argument is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true } && parameterRefKind == RefKind.Ref && parameters.ParameterTypes[argumentPosition].Type is NamedTypeSymbol { IsInterpolatedStringHandlerType: true, IsValueType: true }) { // For interpolated strings handlers, we allow an interpolated string expression to be passed as if `ref` was specified // in the source when the handler type is a value type. // https://github.com/dotnet/roslyn/issues/54584 allow binary additions of interpolated strings to match as well. hasInterpolatedStringRefMismatch = true; argumentRefKind = parameterRefKind; } conversion = CheckArgumentForApplicability( candidate, argument, argumentRefKind, parameters.ParameterTypes[argumentPosition].Type, parameterRefKind, ignoreOpenTypes, ref useSiteInfo, forExtensionMethodThisArg, hasInterpolatedStringRefMismatch); if (forExtensionMethodThisArg && !Conversions.IsValidExtensionMethodThisArgConversion(conversion)) { // Return early, without checking conversions of subsequent arguments, // if the instance argument is not convertible to the 'this' parameter, // even when 'completeResults' is requested. This avoids unnecessary // lambda binding in particular, for instance, with LINQ expressions. // Note that BuildArgumentsForErrorRecovery will still bind some number // of overloads for the semantic model. Debug.Assert(badArguments == null); Debug.Assert(conversions == null); return MemberAnalysisResult.BadArgumentConversions(argsToParameters, ImmutableArray.Create(argumentPosition), ImmutableArray.Create(conversion)); } if (!conversion.Exists) { badArguments ??= ArrayBuilder<int>.GetInstance(); badArguments.Add(argumentPosition); } } if (conversions != null) { conversions.Add(conversion); } else if (!conversion.IsIdentity) { conversions = ArrayBuilder<Conversion>.GetInstance(paramCount); conversions.AddMany(Conversion.Identity, argumentPosition); conversions.Add(conversion); } if (badArguments != null && !completeResults) { break; } } MemberAnalysisResult result; var conversionsArray = conversions != null ? conversions.ToImmutableAndFree() : default(ImmutableArray<Conversion>); if (badArguments != null) { result = MemberAnalysisResult.BadArgumentConversions(argsToParameters, badArguments.ToImmutableAndFree(), conversionsArray); } else { result = MemberAnalysisResult.NormalForm(argsToParameters, conversionsArray, hasAnyRefOmittedArgument); } return result; } private Conversion CheckArgumentForApplicability( Symbol candidate, // method or property BoundExpression argument, RefKind argRefKind, TypeSymbol parameterType, RefKind parRefKind, bool ignoreOpenTypes, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forExtensionMethodThisArg, bool hasInterpolatedStringRefMismatch) { // Spec 7.5.3.1 // For each argument in A, the parameter passing mode of the argument (i.e., value, ref, or out) is identical // to the parameter passing mode of the corresponding parameter, and // - for a value parameter or a parameter array, an implicit conversion (§6.1) // exists from the argument to the type of the corresponding parameter, or // - for a ref or out parameter, the type of the argument is identical to the type of the corresponding parameter. // effective RefKind has to match unless argument expression is of the type dynamic. // This is a bug in Dev11 which we also implement. // The spec is correct, this is not an intended behavior. We don't fix the bug to avoid a breaking change. if (!(argRefKind == parRefKind || (argRefKind == RefKind.None && argument.HasDynamicType()))) { return Conversion.NoConversion; } // TODO (tomat): the spec wording isn't final yet // Spec 7.5.4: Compile-time checking of dynamic overload resolution: // - Then, any parameter whose type is open (i.e. contains a type parameter; see §4.4.2) is elided, along with its corresponding parameter(s). // and // - The modified parameter list for F is applicable to the modified argument list in terms of section §7.5.3.1 if (ignoreOpenTypes && parameterType.ContainsTypeParameter(parameterContainer: (MethodSymbol)candidate)) { // defer applicability check to runtime: return Conversion.ImplicitDynamic; } var argType = argument.Type; if (argument.Kind == BoundKind.OutVariablePendingInference || argument.Kind == BoundKind.OutDeconstructVarPendingInference || (argument.Kind == BoundKind.DiscardExpression && (object)argType == null)) { Debug.Assert(argRefKind != RefKind.None); // Any parameter type is good, we'll use it for the var local. return Conversion.Identity; } if (argRefKind == RefKind.None || hasInterpolatedStringRefMismatch) { var conversion = forExtensionMethodThisArg ? Conversions.ClassifyImplicitExtensionMethodThisArgConversion(argument, argument.Type, parameterType, ref useSiteInfo) : Conversions.ClassifyImplicitConversionFromExpression(argument, parameterType, ref useSiteInfo); Debug.Assert((!conversion.Exists) || conversion.IsImplicit, "ClassifyImplicitConversion should only return implicit conversions"); if (hasInterpolatedStringRefMismatch && !conversion.IsInterpolatedStringHandler) { // We allowed a ref mismatch under the assumption the conversion would be an interpolated string handler conversion. If it's not, then there was // actually no conversion because of the refkind mismatch. return Conversion.NoConversion; } return conversion; } if ((object)argType != null && Conversions.HasIdentityConversion(argType, parameterType)) { return Conversion.Identity; } else { return Conversion.NoConversion; } } private static TMember GetConstructedFrom<TMember>(TMember member) where TMember : Symbol { switch (member.Kind) { case SymbolKind.Property: return member; case SymbolKind.Method: return (TMember)(Symbol)(member as MethodSymbol).ConstructedFrom; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } }
1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Test/Semantic/Semantics/DelegateTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; private static readonly string s_expressionOfTDelegateTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression0`1"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions_01() { var source = @"using System; class Program { static void Main() { object o = Main; ICloneable c = Main; Delegate d = Main; MulticastDelegate m = Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20), // (7,24): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // Delegate d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(8, 22), // (9,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)Main; var c = (ICloneable)Main; var d = (Delegate)Main; var m = (MulticastDelegate)Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'method' to 'object' // var o = (object)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)Main").WithArguments("method", "object").WithLocation(6, 17), // (7,17): error CS0030: Cannot convert type 'method' to 'ICloneable' // var c = (ICloneable)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(ICloneable)Main").WithArguments("method", "System.ICloneable").WithLocation(7, 17), // (8,17): error CS0030: Cannot convert type 'method' to 'Delegate' // var d = (Delegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Delegate)Main").WithArguments("method", "System.Delegate").WithLocation(8, 17), // (9,17): error CS0030: Cannot convert type 'method' to 'MulticastDelegate' // var m = (MulticastDelegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(MulticastDelegate)Main").WithArguments("method", "System.MulticastDelegate").WithLocation(9, 17)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_03() { var source = @"class Program { static void Main() { System.Linq.Expressions.Expression e = F; e = (System.Linq.Expressions.Expression)F; System.Linq.Expressions.LambdaExpression l = F; l = (System.Linq.Expressions.LambdaExpression)F; } static int F() => 1; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0030: Cannot convert type 'method' to 'Expression' // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.Expression)F").WithArguments("method", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0030: Cannot convert type 'method' to 'LambdaExpression' // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.Expression)F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); } [Fact] public void MethodGroupConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F() { } static void F(object o) { } static void Main() { object o = F; ICloneable c = F; Delegate d = F; MulticastDelegate m = F; Expression e = F; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,20): error CS8917: The delegate type could not be inferred. // object o = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(9, 20), // (10,24): error CS8917: The delegate type could not be inferred. // ICloneable c = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(10, 24), // (11,22): error CS8917: The delegate type could not be inferred. // Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(11, 22), // (12,31): error CS8917: The delegate type could not be inferred. // MulticastDelegate m = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(12, 31), // (13,24): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(13, 24)); } [Fact] public void LambdaConversions_01() { var source = @"using System; class Program { static void Main() { object o = () => { }; ICloneable c = () => { }; Delegate d = () => { }; MulticastDelegate m = () => { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)(() => { }); var c = (ICloneable)(() => { }); var d = (Delegate)(() => { }); var m = (MulticastDelegate)(() => { }); Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,26): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // var o = (object)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 26), // (7,30): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // var c = (ICloneable)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 30), // (8,28): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var d = (Delegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 28), // (9,37): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // var m = (MulticastDelegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_03() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression e = () => 1; Report(e); e = (Expression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(7, 24), // (9,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 26)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression e = () => 1; Report(e); e = (LambdaExpression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 30), // (9,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // e = (LambdaExpression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 32)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Delegate d = x => x; object o = (object)(x => x); Expression e = x => x; e = (Expression)(x => x); LambdaExpression l = x => x; l = (LambdaExpression)(x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 22), // (8,29): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "object").WithLocation(8, 29), // (9,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 24), // (10,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(10, 26), // (11,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(11, 30), // (12,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(12, 32)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,22): error CS8917: The delegate type could not be inferred. // Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(7, 22), // (8,29): error CS8917: The delegate type could not be inferred. // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 29), // (9,24): error CS8917: The delegate type could not be inferred. // Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 24), // (10,26): error CS8917: The delegate type could not be inferred. // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(10, 26), // (11,30): error CS8917: The delegate type could not be inferred. // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 30), // (12,32): error CS8917: The delegate type could not be inferred. // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(12, 32)); } [Fact] public void LambdaConversions_06() { var sourceA = @"namespace System.Linq.Expressions { public class LambdaExpression<T> { } }"; var sourceB = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression<Func<int>> l = () => 1; l = (LambdaExpression<Func<int>>)(() => 2); } }"; var expectedDiagnostics = new[] { // (7,41): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // LambdaExpression<Func<int>> l = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(7, 41), // (8,43): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // l = (LambdaExpression<Func<int>>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(8, 43) }; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaConversions_07() { var source = @"using System; class Program { static void Main() { System.Delegate d = () => Main; System.Linq.Expressions.Expression e = () => Main; Report(d); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Action] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Action]] "); } [Fact] public void AnonymousMethod_01() { var source = @"using System; class Program { static void Main() { object o = delegate () { }; ICloneable c = delegate () { }; Delegate d = delegate () { }; MulticastDelegate m = delegate () { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert anonymous method to type 'object' because it is not a delegate type // object o = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert anonymous method to type 'ICloneable' because it is not a delegate type // ICloneable c = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // Delegate d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert anonymous method to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void AnonymousMethod_02() { var source = @"using System.Linq.Expressions; class Program { static void Main() { System.Linq.Expressions.Expression e = delegate () { return 1; }; e = (Expression)delegate () { return 2; }; LambdaExpression l = delegate () { return 3; }; l = (LambdaExpression)delegate () { return 4; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,48): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 1; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(6, 48), // (7,25): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 2; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,30): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 3; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 30), // (9,31): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 4; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 31)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,48): error CS1946: An anonymous method expression cannot be converted to an expression tree // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 1; }").WithLocation(6, 48), // (7,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(Expression)delegate () { return 2; }").WithLocation(7, 13), // (8,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 3; }").WithLocation(8, 30), // (9,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(LambdaExpression)delegate () { return 4; }").WithLocation(9, 13)); } [Fact] public void DynamicConversion() { var source = @"using System; class Program { static void Main() { dynamic d; d = Main; d = () => 1; } static void Report(dynamic d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'dynamic'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "dynamic").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert lambda expression to type 'dynamic' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "dynamic").WithLocation(8, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", "System.Func<System.Action<System.String[]>>"); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); // Distinct names for distinct signatures with > 16 parameters: https://github.com/dotnet/roslyn/issues/55570 yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, ref int _17) => { }", "<>A{100000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, in int _17) => { }", "<>A{300000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } private static bool HaveMatchingSignatures(IMethodSymbol methodA, IMethodSymbol methodB) { return MemberSignatureComparer.MethodGroupSignatureComparer.Equals(methodA.GetSymbol<MethodSymbol>(), methodB.GetSymbol<MethodSymbol>()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (5,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(5, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (6,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(6, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } [Fact] public void Member_01() { var source = @"using System; class Program { static void Main() { Console.WriteLine((() => { }).GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // Console.WriteLine((() => { }).GetType()); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(() => { }).GetType").WithArguments(".", "lambda expression").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void Member_02() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Main.GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0119: 'Program.Main()' is a method, which is not valid in the given context // Console.WriteLine(Main.GetType()); Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS0570: 'A.F1(object)' is not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F1").WithArguments("A.F1(object)").WithLocation(10, 16), // (10,16): error CS0648: '' is a type not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BogusType, "A.F1").WithArguments("").WithLocation(10, 16), // (11,16): error CS0570: 'A.F2()' is not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F2").WithArguments("A.F2()").WithLocation(11, 16), // (11,16): error CS0648: '' is a type not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BogusType, "A.F2").WithArguments("").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } // Expression<T> not derived from Expression. private static MetadataReference GetCorlibWithExpressionOfTNotDerivedType() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_01() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_02() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static T F<T>(T t) where T : System.Linq.Expressions.Expression => t; static void Main() { var e = F(() => 1); } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (6,17): error CS0311: The type 'System.Linq.Expressions.Expression<System.Func<int>>' cannot be used as type parameter 'T' in the generic type or method 'Program.F<T>(T)'. There is no implicit reference conversion from 'System.Linq.Expressions.Expression<System.Func<int>>' to 'System.Linq.Expressions.Expression'. // var e = F(() => 1); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("Program.F<T>(T)", "System.Linq.Expressions.Expression", "T", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(6, 17)); } /// <summary> /// System.Linq.Expressions as a type rather than a namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsType() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace System.Linq { public class Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } } }"; var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e1 = () => 1; System.Linq.Expressions.LambdaExpression e2 = () => 2; System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,49): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression' because it is not a delegate type // System.Linq.Expressions.Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 49), // (6,55): error CS1660: Cannot convert lambda expression to type 'Expressions.LambdaExpression' because it is not a delegate type // System.Linq.Expressions.LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(6, 55), // (7,67): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression<Func<int>>' because it is not a delegate type // System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(7, 67)); } /// <summary> /// System.Linq.Expressions as a nested namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsNestedNamespace() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace Root.System.Linq.Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } }"; var sourceB = @"using System; using Root.System.Linq.Expressions; class Program { static void Main() { Expression e1 = () => 1; LambdaExpression e2 = () => 2; Expression<Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (7,25): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,31): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "Root.System.Linq.Expressions.LambdaExpression").WithLocation(8, 31), // (9,36): error CS1660: Cannot convert lambda expression to type 'Expression<Func<int>>' because it is not a delegate type // Expression<Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(9, 36)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "M(Action<string> a)"); // Breaking change from C#9 which binds to M(Action<string> a). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: "M<T>(T t)"); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M(object x, Action y) E.M(object x, Action y) "); // Breaking change from C#9 which binds to E.M(object x, Action y). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"C.M(object y) C.M(object y) "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_12() { var source = @"using System; #nullable enable var app = new WebApp(); app.Map(""/sub1"", builder => { builder.UseAuth(); }); app.Map(""/sub2"", (IAppBuilder builder) => { builder.UseAuth(); }); class WebApp : IAppBuilder, IRouteBuilder { public void UseAuth() { } } interface IAppBuilder { void UseAuth(); } interface IRouteBuilder { } static class AppBuilderExtensions { public static IAppBuilder Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) => app; } static class RouteBuilderExtensions { public static IRouteBuilder Map(this IRouteBuilder routes, string path, Delegate callback) => routes; } struct PathSring { public PathSring(string? path) { Path = path; } public string? Path { get; } public static implicit operator PathSring(string? s) => new PathSring(s); public static implicit operator string?(PathSring path) => path.Path; }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (8,5): error CS0121: The call is ambiguous between the following methods or properties: 'AppBuilderExtensions.Map(IAppBuilder, PathSring, Action<IAppBuilder>)' and 'RouteBuilderExtensions.Map(IRouteBuilder, string, Delegate)' // app.Map("/sub2", (IAppBuilder builder) => Diagnostic(ErrorCode.ERR_AmbigCall, "Map").WithArguments("AppBuilderExtensions.Map(IAppBuilder, PathSring, System.Action<IAppBuilder>)", "RouteBuilderExtensions.Map(IRouteBuilder, string, System.Delegate)").WithLocation(8, 5) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_13() { var source = @"using System; class Program { static void Main() { F(1, () => { }); F(2, Main); } static void F(object obj, Action a) { } static void F(int i, Delegate d) { } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(object, Action)' and 'Program.F(int, Delegate)' // F(1, () => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(object, System.Action)", "Program.F(int, System.Delegate)").WithLocation(6, 9), // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(object, Action)' and 'Program.F(int, Delegate)' // F(2, Main); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(object, System.Action)", "Program.F(int, System.Delegate)").WithLocation(7, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_14() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { F(() => 1, 2); } static void F(Expression<Func<object>> f, object obj) { } static void F(Expression e, int i) { } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Expression<Func<object>>, object)' and 'Program.F(Expression, int)' // F(() => 1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Linq.Expressions.Expression<System.Func<object>>, object)", "Program.F(System.Linq.Expressions.Expression, int)").WithLocation(7, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_15() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(T t) { } static void F(StringAction a) { } static void M(string arg) { } static void Main() { F((string s) => { }); // C#9: F(StringAction) F(M); // C#9: F(StringAction) } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); // Breaking change from C#9 which binds calls to F(StringAction). comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(T)' and 'Program.F(StringAction)' // F((string s) => { }); // C#9: F(StringAction) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(T)", "Program.F(StringAction)").WithLocation(9, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(T)' and 'Program.F(StringAction)' // F(M); // C#9: F(StringAction) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(T)", "Program.F(StringAction)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_16() { var source = @"using System; class Program { static void F(Func<Func<object>> f, int i) => Report(f); static void F(Func<Func<int>> f, object o) => Report(f); static void Main() { F(() => () => 1, 2); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"System.Func`1[System.Func`1[System.Object]]"); // Breaking change from C#9 which binds calls to F(Func<Func<object>>, int). var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Func<Func<object>>, int)' and 'Program.F(Func<Func<int>>, object)' // F(() => () => 1, 2); // C#9: F(Func<Func<object>>, int) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Func<System.Func<object>>, int)", "Program.F(System.Func<System.Func<int>>, object)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_17() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(System.Action<T> a) { } static void F(StringAction a) { } static void Main() { F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F(StringAction)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_18() { var source = @"delegate void StringAction(string arg); class Program { static void F0<T>(System.Action<T> a) { } static void F1<T>(System.Action<T> a) { } static void F1(StringAction a) { } static void M(string arg) { } static void Main() { F0(M); F1(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F0<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F0(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F0").WithArguments("Program.F0<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_19() { var source = @"delegate void MyAction<T>(T arg); class Program { static void F<T>(System.Action<T> a) { } static void F<T>(MyAction<T> a) { } static void M(string arg) { } static void Main() { F((string s) => { }); F(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F<T>(MyAction<T>)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F<T>(MyAction<T>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_20() { var source = @"using System; delegate void StringAction(string s); class Program { static void F(Action<string> a) { } static void F(StringAction a) { } static void M(string s) { } static void Main() { F(M); F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F(M); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(11, 9)); } [Fact] public void OverloadResolution_21() { var source = @"using System; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Delegate>(); c.F(() => (Action)null); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Delegate]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_22() { var source = @"using System; using System.Linq.Expressions; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Expression>(); c.F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Linq.Expressions.Expression]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (15,11): error CS0121: The call is ambiguous between the following methods or properties: 'C<T>.F(T)' and 'C<T>.F(Func<T>)' // c.F(() => Expression.Constant(1)); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C<T>.F(T)", "C<T>.F(System.Func<T>)").WithLocation(15, 11) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [Fact] public void OverloadResolution_23() { var source = @"using System; class Program { static void F(Delegate d) => Console.WriteLine(""F(Delegate d)""); static void F(Func<object> f) => Console.WriteLine(""F(Func<int> f)""); static void Main() { F(() => 1); } }"; string expectedOutput = "F(Func<int> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_24() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) => Console.WriteLine(""F(Expression e)""); static void F(Func<Expression> f) => Console.WriteLine(""F(Func<Expression> f)""); static void Main() { F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<Expression> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Expression)' and 'Program.F(Func<Expression>)' // F(() => Expression.Constant(1)); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Linq.Expressions.Expression)", "Program.F(System.Func<System.Linq.Expressions.Expression>)").WithLocation(9, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [Fact] public void BestCommonType_01() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { StringIntDelegate d = M; var a1 = new[] { d, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => int.Parse(s), d }; Report(a1[1]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_02() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void F(bool b) { StringIntDelegate d = M; var c1 = b ? d : ((string s) => int.Parse(s)); var c2 = b ? ((string s) => int.Parse(s)) : d; Report(c1); Report(c2); } static void Main() { F(false); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_03() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return (StringIntDelegate)M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return (StringIntDelegate)M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"StringIntDelegate StringIntDelegate"); } [Fact] public void BestCommonType_04() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_05() { var source = @"using System; class Program { static int M1(string s) => s.Length; static int M2(string s) => int.Parse(s); static void Main() { var a1 = new[] { M1, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => s.Length, M2 }; Report(a1[1]); Report(a2[1]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { M1, (string s) => int.Parse(s) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { M1, (string s) => int.Parse(s) }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (string s) => s.Length, M2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (string s) => s.Length, M2 }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_06() { var source = @"using System; class Program { static void F1<T>(T t) { } static T F2<T>() => default; static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object>, F2<string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object>, F2<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object>, F2<string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Func`1[System.Object]"); } [Fact] public void BestCommonType_07() { var source = @"class Program { static void F1<T>(T t) { } static T F2<T>() => default; static T F3<T>(T t) => t; static void Main() { var a1 = new[] { F1<int>, F1<object> }; var a2 = new[] { F2<nint>, F2<System.IntPtr> }; var a3 = new[] { F3<string>, F3<object> }; } }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<int>, F1<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<int>, F1<object> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<nint>, F2<System.IntPtr> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<nint>, F2<System.IntPtr> }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F3<string>, F3<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F3<string>, F3<object> }").WithLocation(10, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_08() { var source = @"#nullable enable using System; class Program { static void F<T>(T t) { } static void Main() { var a1 = new[] { F<string?>, F<string> }; var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<string?>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<string?>, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<(int X, object Y)>, F<(int, dynamic)> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Action`1[System.ValueTuple`2[System.Int32,System.Object]]"); } [Fact] public void BestCommonType_09() { var source = @"using System; class Program { static void Main() { var a1 = new[] { (object o) => { }, (string s) => { } }; var a2 = new[] { () => (object)null, () => (string)null }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object o) => { }, (string s) => { } }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { () => (object)null, () => (string)null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => (object)null, () => (string)null }").WithLocation(7, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,26): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(6, 26), // (6,34): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(6, 34)); } [Fact] public void BestCommonType_10() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<string>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<string>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<string>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000004}`2[System.String,System.Object] <>A{00000001}`2[System.Object,System.String]"); } [Fact] [WorkItem(55909, "https://github.com/dotnet/roslyn/issues/55909")] public void BestCommonType_11() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, object> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, object> }").WithLocation(9, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/55909: ConversionsBase.HasImplicitSignatureConversion() // relies on the variance of FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_12() { var source = @"class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, F<string> }; var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; } }"; var expectedDiagnostics = new[] { // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, F<string> }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_13() { var source = @"using System; class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, null }; var a2 = new[] { default, F<string> }; var a3 = new[] { null, default, (object x, ref string y) => { } }; Report(a1[0]); Report(a2[1]); Report(a3[2]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, null }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { default, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { default, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { null, default, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null, default, (object x, ref string y) => { } }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000001}`1[System.Object] <>A{00000001}`1[System.String] <>A{00000004}`2[System.Object,System.String] "); } /// <summary> /// Best common type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void BestCommonType_NoInferredSignature() { var source = @"class Program { static void F1() { } static int F1(int i) => i; static void F2() { } static void Main() { var a1 = new[] { F1 }; var a2 = new[] { F1, F2 }; var a3 = new[] { F2, F1 }; var a4 = new[] { x => x }; var a5 = new[] { x => x, (int y) => y }; var a6 = new[] { (int y) => y, static x => x }; var a7 = new[] { x => x, F1 }; var a8 = new[] { F1, (int y) => y }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F1, F2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, F2 }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F2, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2, F1 }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var a5 = new[] { x => x, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, (int y) => y }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var a6 = new[] { (int y) => y, static x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (int y) => y, static x => x }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var a8 = new[] { F1, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, (int y) => y }").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18)); } [Fact] public void ArrayInitializer_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Func<int>[] { () => 1 }; var a2 = new Expression<Func<int>>[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void ArrayInitializer_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Delegate[] { () => 1 }; var a2 = new Expression[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,35): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var a1 = new Delegate[] { () => 1 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 35), // (8,37): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // var a2 = new Expression[] { () => 2 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(8, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"); } [Fact] public void ArrayInitializer_03() { var source = @"using System; class Program { static void Main() { var a1 = new[] { () => 1 }; Report(a1[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { () => 1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => 1 }").WithLocation(6, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32]"); } [Fact] public void ConditionalOperator_01() { var source = @"class Program { static void F<T>(T t) { } static void Main() { var c1 = F<object> ?? F<string>; var c2 = ((object o) => { }) ?? ((string s) => { }); var c3 = F<string> ?? ((object o) => { }); } }"; var expectedDiagnostics = new[] { // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // var c1 = F<object> ?? F<string>; Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<object> ?? F<string>").WithArguments("??", "method group", "method group").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'lambda expression' and 'lambda expression' // var c2 = ((object o) => { }) ?? ((string s) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "((object o) => { }) ?? ((string s) => { })").WithArguments("??", "lambda expression", "lambda expression").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'lambda expression' // var c3 = F<string> ?? ((object o) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<string> ?? ((object o) => { })").WithArguments("??", "method group", "lambda expression").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaReturn_01() { var source = @"using System; class Program { static void Main() { var a1 = () => () => 1; var a2 = () => Main; Report(a1()); Report(a2()); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32] System.Action"); } [Fact] public void InferredType_MethodGroup() { var source = @"class Program { static void Main() { System.Delegate d = Main; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Fact] public void InferredType_LambdaExpression() { var source = @"class Program { static void Main() { System.Delegate d = () => { }; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_01() { var source = @"using System; class Program { static void Main() { Report(() => { return; }); Report((bool b) => { if (b) return; }); Report((bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action`1[System.Boolean] System.Action`1[System.Boolean] "); } [Fact] public void InferredReturnType_02() { var source = @"using System; class Program { static void Main() { Report(async () => { return; }); Report(async (bool b) => { if (b) return; }); Report(async (bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] "); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_03() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return null; }); Report((bool b) => { if (b) return; else return null; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return null; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return null; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_04() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return default; }); Report((bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return default; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return default; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [Fact] public void ExplicitReturnType_01() { var source = @"using System; class Program { static void Main() { Report(object () => { return; }); Report(object (bool b) => { if (b) return null; }); Report(object (bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,31): error CS0126: An object of a type convertible to 'object' is required // Report(object () => { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(6, 31), // (7,32): error CS1643: Not all code paths return a value in lambda expression of type 'Func<bool, object>' // Report(object (bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<bool, object>").WithLocation(7, 32), // (8,44): error CS0126: An object of a type convertible to 'object' is required // Report(object (bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(8, 44)); } [Fact] public void TypeInference_Constraints_01() { var source = @"using System; using System.Linq.Expressions; class Program { static T F1<T>(T t) where T : Delegate => t; static T F2<T>(T t) where T : Expression => t; static void Main() { Report(F1((int i) => { })); Report(F2(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((int i) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F2<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Action`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_02() { var source = @"using System; using System.Linq.Expressions; class A<T> { public static U F<U>(U u) where U : T => u; } class B { static void Main() { Report(A<object>.F(() => 1)); Report(A<ICloneable>.F(() => 1)); Report(A<Delegate>.F(() => 1)); Report(A<MulticastDelegate>.F(() => 1)); Report(A<Func<int>>.F(() => 1)); Report(A<Expression>.F(() => 1)); Report(A<LambdaExpression>.F(() => 1)); Report(A<Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_03() { var source = @"using System; using System.Linq.Expressions; class A<T, U> where U : T { public static V F<V>(V v) where V : U => v; } class B { static void Main() { Report(A<object, object>.F(() => 1)); Report(A<object, Delegate>.F(() => 1)); Report(A<object, Func<int>>.F(() => 1)); Report(A<Delegate, Func<int>>.F(() => 1)); Report(A<object, Expression>.F(() => 1)); Report(A<object, Expression<Func<int>>>.F(() => 1)); Report(A<Expression, LambdaExpression>.F(() => 1)); Report(A<Expression, Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_MatchingSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(string s) => s.Length; static void F2(string s) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_DistinctSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(object o) => o.GetHashCode(); static void F2(object o) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static T M<T>(T x, T y) => x; static int F1(int i) => i; static void F1() { } static T F2<T>(T t) => t; static void Main() { var f1 = M(x => x, (int y) => y); var f2 = M(F1, F2<int>); var f3 = M(F2<object>, z => z); Report(f1); Report(f2); Report(f3); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(F1, F2<int>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M(F2<object>, z => z); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(12, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Object,System.Object] "); } [Fact] public void TypeInference_02() { var source = @"using System; class Program { static T M<T>(T x, T y) where T : class => x ?? y; static T F<T>() => default; static void Main() { var f1 = M(F<object>, null); var f2 = M(default, F<string>); var f3 = M((object x, ref string y) => { }, default); var f4 = M(null, (ref object x, string y) => { }); Report(f1); Report(f2); Report(f3); Report(f4); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(F<object>, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(8, 18), // (9,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(default, F<string>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(9, 18), // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M((object x, ref string y) => { }, default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f4 = M(null, (ref object x, string y) => { }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Object] System.Func`1[System.String] <>A{00000004}`2[System.Object,System.String] <>A{00000001}`2[System.Object,System.String] "); } [Fact] public void TypeInference_LowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (string s) => { })); Report(F(() => 2, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (object o) => { })); Report(F(() => 1.0, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (11,22): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(11, 22), // (11,30): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(11, 30), // (12,24): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(12, 24), // (12,24): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("lambda expression").WithLocation(12, 24) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_02() { var source = @"using System; class Program { static T F<T>(T x, T y) => y; static void Main() { Report(F((string s) => { }, (object o) => { })); Report(F(() => string.Empty, () => new object())); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(7, 16), // (8,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(() => string.Empty, () => new object())); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(8, 16)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(7, 37), // (7,45): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(7, 45)); } [Fact] public void TypeInference_UpperAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<int>> a2 = null; Report(F1(a1, (string s) => { })); Report(F2(() => 2, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<object>> a2 = null; Report(F1(a1, (object o) => { })); Report(F2(() => string.Empty, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,23): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 23), // (12,31): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 31) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,42): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(10, 50) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F1(ref d1, (string s) => { })); Report(F2(() => 2, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<object> d2 = () => new object(); Report(F1(ref d1, (object o) => { })); Report(F2(() => string.Empty, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,27): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 27), // (12,35): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 35) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(in T x, T y) => y; static T F2<T>(T x, in T y) => y; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,16): error CS0411: The type arguments for method 'Program.F1<T>(in T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(in T, T)").WithLocation(10, 16), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): error CS1661: Cannot convert lambda expression to type 'Action<D1<string>>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<D1<string>>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'D1<string>' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "D1<string>").WithLocation(10, 50), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16)); } [Fact] public void TypeInference_Nested_01() { var source = @"delegate void D<T>(T t); class Program { static T F1<T>(T t) => t; static D<T> F2<T>(D<T> d) => d; static void Main() { F2(F1((string s) => { })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(D<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(D<T>)").WithLocation(8, 9)); } [Fact] public void TypeInference_Nested_02() { var source = @"using System.Linq.Expressions; class Program { static T F1<T>(T x) => throw null; static Expression<T> F2<T>(Expression<T> e) => e; static void Main() { F2(F1((object x1) => 1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((object x1) => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<T>)").WithLocation(8, 9)); } /// <summary> /// Method type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void TypeInference_NoInferredSignature() { var source = @"class Program { static void F1() { } static void F1(int i) { } static void F2() { } static T M1<T>(T t) => t; static T M2<T>(T x, T y) => x; static void Main() { var a1 = M1(F1); var a2 = M2(F1, F2); var a3 = M2(F2, F1); var a4 = M1(x => x); var a5 = M2(x => x, (int y) => y); var a6 = M2((int y) => y, x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a2 = M2(F1, F2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a3 = M2(F2, F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(12, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18), // (14,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a5 = M2(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(14, 18), // (15,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a6 = M2((int y) => y, x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18)); } [Fact] public void Variance() { var source = @"using System; delegate void StringAction(string s); class Program { static void Main() { Action<string> a1 = s => { }; Action<string> a2 = (string s) => { }; Action<string> a3 = (object o) => { }; Action<string> a4 = (Action<object>)((object o) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,29): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(9, 29), // (9,37): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(9, 37)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } [Fact] public void BinaryOperator() { var source = @"using System; class Program { static void Main() { var b1 = (() => { }) == null; var b2 = null == Main; var b3 = Main == (() => { }); Console.WriteLine((b1, b2, b3)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and '<null>' // var b1 = (() => { }) == null; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => { }) == null").WithArguments("==", "lambda expression", "<null>").WithLocation(6, 18), // (7,18): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // var b2 = null == Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == Main").WithArguments("==", "<null>", "method group").WithLocation(7, 18), // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'lambda expression' // var b3 = Main == (() => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main == (() => { })").WithArguments("==", "method group", "lambda expression").WithLocation(8, 18)); CompileAndVerify(source, expectedOutput: "(False, False, False)"); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_18() { var source = @"using System; class Program { static void Main() { Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { return 1; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, out int _17) => { _17 = 0; return 2; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, ref int _17) => { return 3; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, in int _17) => { return 4; }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>F`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{200000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{100000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{300000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_19() { var source = @"using System; class Program { static void F1(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18) { } static void F2(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, out object _18) { _18 = null; } static void F3(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, ref object _18) { } static void F4(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, in object _18) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{800000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{400000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{c00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_20() { var source = @"using System; class Program { static void F1( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, int _33) { } static void F2( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, out int _33) { _33 = 0; } static void F3( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, ref int _33) { } static void F4( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, in int _33) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{4000000000000000\,00000000}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000002}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000001}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000003}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] "); } /// <summary> /// Synthesized delegate types should only be emitted if used. /// </summary> [Fact] [WorkItem(55896, "https://github.com/dotnet/roslyn/issues/55896")] public void SynthesizedDelegateTypes_21() { var source = @"using System; delegate void D2(object x, ref object y); delegate void D4(out object x, ref object y); class Program { static void F1(ref object x, object y) { } static void F2(object x, ref object y) { } static void Main() { var d1 = F1; D2 d2 = F2; var d3 = (ref object x, out object y) => { y = null; }; D4 d4 = (out object x, ref object y) => { x = null; }; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, validator: validator, expectedOutput: @"<>A{00000001}`2[System.Object,System.Object] D2 <>A{00000009}`2[System.Object,System.Object] D4"); static void validator(PEAssembly assembly) { var reader = assembly.GetMetadataReader(); var actualTypes = reader.GetTypeDefNames().Select(h => reader.GetString(h)).ToArray(); // https://github.com/dotnet/roslyn/issues/55896: Should not include <>A{00000004}`2 or <>A{00000006}`2. string[] expectedTypes = new[] { "<Module>", "<>A{00000001}`2", "<>A{00000004}`2", "<>A{00000006}`2", "<>A{00000009}`2", "D2", "D4", "Program", "<>c", }; AssertEx.Equal(expectedTypes, actualTypes); } } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; private static readonly string s_expressionOfTDelegateTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression0`1"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions_01() { var source = @"using System; class Program { static void Main() { object o = Main; ICloneable c = Main; Delegate d = Main; MulticastDelegate m = Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20), // (7,24): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // Delegate d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(8, 22), // (9,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)Main; var c = (ICloneable)Main; var d = (Delegate)Main; var m = (MulticastDelegate)Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'method' to 'object' // var o = (object)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)Main").WithArguments("method", "object").WithLocation(6, 17), // (7,17): error CS0030: Cannot convert type 'method' to 'ICloneable' // var c = (ICloneable)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(ICloneable)Main").WithArguments("method", "System.ICloneable").WithLocation(7, 17), // (8,17): error CS0030: Cannot convert type 'method' to 'Delegate' // var d = (Delegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Delegate)Main").WithArguments("method", "System.Delegate").WithLocation(8, 17), // (9,17): error CS0030: Cannot convert type 'method' to 'MulticastDelegate' // var m = (MulticastDelegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(MulticastDelegate)Main").WithArguments("method", "System.MulticastDelegate").WithLocation(9, 17)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_03() { var source = @"class Program { static void Main() { System.Linq.Expressions.Expression e = F; e = (System.Linq.Expressions.Expression)F; System.Linq.Expressions.LambdaExpression l = F; l = (System.Linq.Expressions.LambdaExpression)F; } static int F() => 1; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0030: Cannot convert type 'method' to 'Expression' // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.Expression)F").WithArguments("method", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0030: Cannot convert type 'method' to 'LambdaExpression' // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.Expression)F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); } [Fact] public void MethodGroupConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F() { } static void F(object o) { } static void Main() { object o = F; ICloneable c = F; Delegate d = F; MulticastDelegate m = F; Expression e = F; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,20): error CS8917: The delegate type could not be inferred. // object o = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(9, 20), // (10,24): error CS8917: The delegate type could not be inferred. // ICloneable c = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(10, 24), // (11,22): error CS8917: The delegate type could not be inferred. // Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(11, 22), // (12,31): error CS8917: The delegate type could not be inferred. // MulticastDelegate m = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(12, 31), // (13,24): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(13, 24)); } [Fact] public void LambdaConversions_01() { var source = @"using System; class Program { static void Main() { object o = () => { }; ICloneable c = () => { }; Delegate d = () => { }; MulticastDelegate m = () => { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)(() => { }); var c = (ICloneable)(() => { }); var d = (Delegate)(() => { }); var m = (MulticastDelegate)(() => { }); Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,26): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // var o = (object)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 26), // (7,30): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // var c = (ICloneable)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 30), // (8,28): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var d = (Delegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 28), // (9,37): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // var m = (MulticastDelegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_03() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression e = () => 1; Report(e); e = (Expression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(7, 24), // (9,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 26)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression e = () => 1; Report(e); e = (LambdaExpression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 30), // (9,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // e = (LambdaExpression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 32)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Delegate d = x => x; object o = (object)(x => x); Expression e = x => x; e = (Expression)(x => x); LambdaExpression l = x => x; l = (LambdaExpression)(x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 22), // (8,29): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "object").WithLocation(8, 29), // (9,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 24), // (10,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(10, 26), // (11,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(11, 30), // (12,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(12, 32)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,22): error CS8917: The delegate type could not be inferred. // Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(7, 22), // (8,29): error CS8917: The delegate type could not be inferred. // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 29), // (9,24): error CS8917: The delegate type could not be inferred. // Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 24), // (10,26): error CS8917: The delegate type could not be inferred. // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(10, 26), // (11,30): error CS8917: The delegate type could not be inferred. // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 30), // (12,32): error CS8917: The delegate type could not be inferred. // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(12, 32)); } [Fact] public void LambdaConversions_06() { var sourceA = @"namespace System.Linq.Expressions { public class LambdaExpression<T> { } }"; var sourceB = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression<Func<int>> l = () => 1; l = (LambdaExpression<Func<int>>)(() => 2); } }"; var expectedDiagnostics = new[] { // (7,41): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // LambdaExpression<Func<int>> l = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(7, 41), // (8,43): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // l = (LambdaExpression<Func<int>>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(8, 43) }; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaConversions_07() { var source = @"using System; class Program { static void Main() { System.Delegate d = () => Main; System.Linq.Expressions.Expression e = () => Main; Report(d); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Action] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Action]] "); } [Fact] public void AnonymousMethod_01() { var source = @"using System; class Program { static void Main() { object o = delegate () { }; ICloneable c = delegate () { }; Delegate d = delegate () { }; MulticastDelegate m = delegate () { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert anonymous method to type 'object' because it is not a delegate type // object o = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert anonymous method to type 'ICloneable' because it is not a delegate type // ICloneable c = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // Delegate d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert anonymous method to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void AnonymousMethod_02() { var source = @"using System.Linq.Expressions; class Program { static void Main() { System.Linq.Expressions.Expression e = delegate () { return 1; }; e = (Expression)delegate () { return 2; }; LambdaExpression l = delegate () { return 3; }; l = (LambdaExpression)delegate () { return 4; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,48): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 1; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(6, 48), // (7,25): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 2; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,30): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 3; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 30), // (9,31): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 4; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 31)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,48): error CS1946: An anonymous method expression cannot be converted to an expression tree // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 1; }").WithLocation(6, 48), // (7,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(Expression)delegate () { return 2; }").WithLocation(7, 13), // (8,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 3; }").WithLocation(8, 30), // (9,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(LambdaExpression)delegate () { return 4; }").WithLocation(9, 13)); } [Fact] public void DynamicConversion() { var source = @"using System; class Program { static void Main() { dynamic d; d = Main; d = () => 1; } static void Report(dynamic d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'dynamic'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "dynamic").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert lambda expression to type 'dynamic' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "dynamic").WithLocation(8, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", "System.Func<System.Action<System.String[]>>"); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); // Distinct names for distinct signatures with > 16 parameters: https://github.com/dotnet/roslyn/issues/55570 yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, ref int _17) => { }", "<>A{100000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, in int _17) => { }", "<>A{300000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } private static bool HaveMatchingSignatures(IMethodSymbol methodA, IMethodSymbol methodB) { return MemberSignatureComparer.MethodGroupSignatureComparer.Equals(methodA.GetSymbol<MethodSymbol>(), methodB.GetSymbol<MethodSymbol>()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (5,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(5, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (6,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(6, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } [Fact] public void Member_01() { var source = @"using System; class Program { static void Main() { Console.WriteLine((() => { }).GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // Console.WriteLine((() => { }).GetType()); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(() => { }).GetType").WithArguments(".", "lambda expression").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void Member_02() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Main.GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0119: 'Program.Main()' is a method, which is not valid in the given context // Console.WriteLine(Main.GetType()); Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS0570: 'A.F1(object)' is not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F1").WithArguments("A.F1(object)").WithLocation(10, 16), // (10,16): error CS0648: '' is a type not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BogusType, "A.F1").WithArguments("").WithLocation(10, 16), // (11,16): error CS0570: 'A.F2()' is not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F2").WithArguments("A.F2()").WithLocation(11, 16), // (11,16): error CS0648: '' is a type not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BogusType, "A.F2").WithArguments("").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } // Expression<T> not derived from Expression. private static MetadataReference GetCorlibWithExpressionOfTNotDerivedType() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_01() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_02() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static T F<T>(T t) where T : System.Linq.Expressions.Expression => t; static void Main() { var e = F(() => 1); } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (6,17): error CS0311: The type 'System.Linq.Expressions.Expression<System.Func<int>>' cannot be used as type parameter 'T' in the generic type or method 'Program.F<T>(T)'. There is no implicit reference conversion from 'System.Linq.Expressions.Expression<System.Func<int>>' to 'System.Linq.Expressions.Expression'. // var e = F(() => 1); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("Program.F<T>(T)", "System.Linq.Expressions.Expression", "T", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(6, 17)); } /// <summary> /// System.Linq.Expressions as a type rather than a namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsType() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace System.Linq { public class Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } } }"; var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e1 = () => 1; System.Linq.Expressions.LambdaExpression e2 = () => 2; System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,49): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression' because it is not a delegate type // System.Linq.Expressions.Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 49), // (6,55): error CS1660: Cannot convert lambda expression to type 'Expressions.LambdaExpression' because it is not a delegate type // System.Linq.Expressions.LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(6, 55), // (7,67): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression<Func<int>>' because it is not a delegate type // System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(7, 67)); } /// <summary> /// System.Linq.Expressions as a nested namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsNestedNamespace() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace Root.System.Linq.Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } }"; var sourceB = @"using System; using Root.System.Linq.Expressions; class Program { static void Main() { Expression e1 = () => 1; LambdaExpression e2 = () => 2; Expression<Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (7,25): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,31): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "Root.System.Linq.Expressions.LambdaExpression").WithLocation(8, 31), // (9,36): error CS1660: Cannot convert lambda expression to type 'Expression<Func<int>>' because it is not a delegate type // Expression<Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(9, 36)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = "M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M(object x, Action y) E.M(object x, Action y) "); // Breaking change from C#9 which binds to E.M(object x, Action y). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"C.M(object y) C.M(object y) "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_12() { var source = @"using System; #nullable enable var app = new WebApp(); app.Map(""/sub1"", builder => { builder.UseAuth(); }); app.Map(""/sub2"", (IAppBuilder builder) => { builder.UseAuth(); }); class WebApp : IAppBuilder, IRouteBuilder { public void UseAuth() { } } interface IAppBuilder { void UseAuth(); } interface IRouteBuilder { } static class AppBuilderExtensions { public static IAppBuilder Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) { Console.WriteLine(""AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback)""); return app; } } static class RouteBuilderExtensions { public static IRouteBuilder Map(this IRouteBuilder routes, string path, Delegate callback) { Console.WriteLine(""RouteBuilderExtensions.Map(this IRouteBuilder routes, string path, Delegate callback)""); return routes; } } struct PathSring { public PathSring(string? path) { Path = path; } public string? Path { get; } public static implicit operator PathSring(string? s) => new PathSring(s); public static implicit operator string?(PathSring path) => path.Path; }"; var expectedOutput = @"AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_13() { var source = @"using System; class Program { static void Main() { F(1, () => { }); F(2, Main); } static void F(object obj, Action a) { Console.WriteLine(""F(object obj, Action a)""); } static void F(int i, Delegate d) { Console.WriteLine(""F(int i, Delegate d)""); } }"; var expectedOutput = @"F(object obj, Action a) F(object obj, Action a) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_14() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { F(() => 1, 2); } static void F(Expression<Func<object>> f, object obj) { Console.WriteLine(""F(Expression<Func<object>> f, object obj)""); } static void F(Expression e, int i) { Console.WriteLine(""F(Expression e, int i)""); } }"; var expectedOutput = @"F(Expression<Func<object>> f, object obj)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_15() { var source = @"using System; delegate void StringAction(string arg); class Program { static void F<T>(T t) { Console.WriteLine(typeof(T).Name); } static void F(StringAction a) { Console.WriteLine(""StringAction""); } static void M(string arg) { } static void Main() { F((string s) => { }); // C#9: F(StringAction) F(M); // C#9: F(StringAction) } }"; var expectedOutput = @"StringAction StringAction "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_16() { var source = @"using System; class Program { static void F(Func<Func<object>> f, int i) => Report(f); static void F(Func<Func<int>> f, object o) => Report(f); static void Main() { F(() => () => 1, 2); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"System.Func`1[System.Func`1[System.Object]]"); // Breaking change from C#9 which binds calls to F(Func<Func<object>>, int). var expectedDiagnostics = new[] { // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Func<Func<object>>, int)' and 'Program.F(Func<Func<int>>, object)' // F(() => () => 1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Func<System.Func<object>>, int)", "Program.F(System.Func<System.Func<int>>, object)").WithLocation(8, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_17() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(System.Action<T> a) { } static void F(StringAction a) { } static void Main() { F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F(StringAction)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_18() { var source = @"delegate void StringAction(string arg); class Program { static void F0<T>(System.Action<T> a) { } static void F1<T>(System.Action<T> a) { } static void F1(StringAction a) { } static void M(string arg) { } static void Main() { F0(M); F1(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F0<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F0(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F0").WithArguments("Program.F0<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_19() { var source = @"delegate void MyAction<T>(T arg); class Program { static void F<T>(System.Action<T> a) { } static void F<T>(MyAction<T> a) { } static void M(string arg) { } static void Main() { F((string s) => { }); F(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F<T>(MyAction<T>)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F<T>(MyAction<T>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_20() { var source = @"using System; delegate void StringAction(string s); class Program { static void F(Action<string> a) { } static void F(StringAction a) { } static void M(string s) { } static void Main() { F(M); F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F(M); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(11, 9)); } [Fact] public void OverloadResolution_21() { var source = @"using System; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Delegate>(); c.F(() => (Action)null); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Delegate]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_22() { var source = @"using System; using System.Linq.Expressions; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Expression>(); c.F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Linq.Expressions.Expression]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_23() { var source = @"using System; class Program { static void F(Delegate d) => Console.WriteLine(""F(Delegate d)""); static void F(Func<object> f) => Console.WriteLine(""F(Func<int> f)""); static void Main() { F(() => 1); } }"; string expectedOutput = "F(Func<int> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_24() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) => Console.WriteLine(""F(Expression e)""); static void F(Func<Expression> f) => Console.WriteLine(""F(Func<Expression> f)""); static void Main() { F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<Expression> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_25() { var source = @"using static System.Console; delegate void D(); class Program { static void F(D d) => WriteLine(""D""); static void F<T>(T t) => WriteLine(typeof(T).Name); static void Main() { F(() => { }); } }"; string expectedOutput = "D"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_26() { var source = @"using System; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F<T>(T t) => Console.WriteLine(typeof(T).Name); static void Main() { int i = 0; F(() => i++); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_27() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F(Expression expression) => Console.WriteLine(""Expression""); static int GetValue() => 0; static void Main() { F(() => GetValue()); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56319, "https://github.com/dotnet/roslyn/issues/56319")] [Fact] public void OverloadResolution_28() { var source = @"using System; var source = new C<int>(); source.Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i); class C<T> { } static class Extensions { public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, Func<TAccumulate> seedFactory, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } }"; string expectedOutput = "(System.Int32, System.Int32, System.Int32)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_29() { var source = @"using System; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Func<object> x, Func<object> y) { Console.WriteLine(""M(Func<object> x, Func<object> y)""); } static void Main() { Func<object> fo = () => new A(); Func<A> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Func<object> x, Func<object> y) M(Func<object> x, Func<object> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_30() { var source = @"using System; class Program { static void M<T>(T t, Func<object> f) { Console.WriteLine(""M<T>(T t, Func<object> f)""); } static void M<T>(Func<object> f, T t) { Console.WriteLine(""M<T>(Func<object> f, T t)""); } static object F() => null; static void Main() { M(F, F); M(() => 1, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(F, F); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(10, 9)); var expectedDiagnostics = new[] { // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(F, F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(9, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(10, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_31() { var source = @"using System; using System.Linq.Expressions; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Expression<Func<object>> e) { Console.WriteLine(""M(Expression<Func<object>> e)""); } static void Main() { M(() => string.Empty); } }"; var expectedOutput = "M(Expression<Func<object>> e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_32() { var source = @"using System; using System.Linq.Expressions; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Expression<Func<object>> x, Expression<Func<object>> y) { Console.WriteLine(""M(Expression<Func<object>> x, Expression<Func<object>> y)""); } static void Main() { Expression<Func<object>> fo = () => new A(); Expression<Func<A>> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Expression<Func<object>> x, Expression<Func<object>> y) M(Expression<Func<object>> x, Expression<Func<object>> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_33() { var source = @"using System; class Program { static void M<T>(object x, T y) { Console.WriteLine(""M<T>(object x, T y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(9, 9), // (10,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(10, 11), // (11,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M<T, U>(T x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_34() { var source = @"using System; class Program { static void M<T, U>(Func<T> x, U y) { Console.WriteLine(""M<T, U>(Func<T> x, U y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(9, 9), // (11,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_35() { var source = @"using System; class Program { static void M(Delegate x, Func<int> y) { Console.WriteLine(""M(Delegate x, Func<int> y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(10, 11)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M(Delegate x, Func<int> y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_36() { var source = @"using System; class Program { static void F<T>(T t) { Console.WriteLine(""F<{0}>({0} t)"", typeof(T).Name); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "System.Delegate").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11)); var expectedOutput = @"F<Action>(Action t) F<Func`1>(Func`1 t)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_37() { var source = @"using System; class Program { static void F(object o) { Console.WriteLine(""F(object o)""); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "object").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(9, 11)); var expectedOutput = @"F(Delegate d) F(Delegate d)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_38() { var source = @"using System; class MyString { public static implicit operator MyString(string s) => new MyString(); } class Program { static void F(Delegate d1, Delegate d2, string s) { Console.WriteLine(""F(Delegate d1, Delegate d2, string s)""); } static void F(Func<int> f, Delegate d, MyString s) { Console.WriteLine(""F(Func<int> f, Delegate d, MyString s)""); } static void Main() { F(() => 1, () => 2, string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 11), // (12,20): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 20)); var expectedDiagnostics = new[] { // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Delegate, Delegate, string)' and 'Program.F(Func<int>, Delegate, MyString)' // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Delegate, System.Delegate, string)", "Program.F(System.Func<int>, System.Delegate, MyString)").WithLocation(12, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_39() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static int F() => 0; static void Main() { M(F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11)); var expectedDiagnostics = new[] { // (10,11): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(10, 11) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_40() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static void Main() { M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 11)); var expectedOutput = @"M(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_41() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(Delegate d) { Console.WriteLine(""M(Delegate d)""); } static int F() => 0; static void Main() { M(F); M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11), // (11,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 11)); var expectedDiagnostics = new[] { // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(() => 1); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(11, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_42() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""96A2DE64-6D44-4DA5-BBA4-25F5F07E0E6B"")] interface I { void F(Delegate d, short s); void F(Action a, ref int i); } class C : I { void I.F(Delegate d, short s) => Console.WriteLine(""I.F(Delegate d, short s)""); void I.F(Action a, ref int i) => Console.WriteLine(""I.F(Action a, ref int i)""); } class Program { static void M(I i) { i.F(() => { }, 1); } static void Main() { M(new C()); } }"; var expectedOutput = @"I.F(Action a, ref int i)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_43() { var source = @"using System; using System.Linq.Expressions; class Program { static int F() => 0; static void Main() { var c = new C(); c.M(F); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); var expectedDiagnostics = new[] { // (9,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // c.M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(9, 13) }; // Breaking change from C#9 which binds to E.M. var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_44() { var source = @"using System; using System.Linq.Expressions; class A { public static void F1(Func<int> f) { Console.WriteLine(""A.F1(Func<int> f)""); } public void F2(Func<int> f) { Console.WriteLine(""A.F2(Func<int> f)""); } } class B : A { public static void F1(Delegate d) { Console.WriteLine(""B.F1(Delegate d)""); } public void F2(Expression e) { Console.WriteLine(""B.F2(Expression e)""); } } class Program { static void Main() { B.F1(() => 1); var b = new B(); b.F2(() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.F1(Func<int> f) A.F2(Func<int> f)"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B.F1(Delegate d) B.F2(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_45() { var source = @"using System; using System.Linq.Expressions; class A { public object this[Func<int> f] => Report(""A.this[Func<int> f]""); public static object Report(string message) { Console.WriteLine(message); return null; } } class B1 : A { public object this[Delegate d] => Report(""B1.this[Delegate d]""); } class B2 : A { public object this[Expression e] => Report(""B2.this[Expression e]""); } class Program { static void Main() { var b1 = new B1(); _ = b1[() => 1]; var b2 = new B2(); _ = b2[() => 2]; } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.this[Func<int> f] A.this[Func<int> f]"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B1.this[Delegate d] B2.this[Expression e]"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_01() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { StringIntDelegate d = M; var a1 = new[] { d, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => int.Parse(s), d }; Report(a1[1]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_02() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void F(bool b) { StringIntDelegate d = M; var c1 = b ? d : ((string s) => int.Parse(s)); var c2 = b ? ((string s) => int.Parse(s)) : d; Report(c1); Report(c2); } static void Main() { F(false); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_03() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return (StringIntDelegate)M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return (StringIntDelegate)M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"StringIntDelegate StringIntDelegate"); } [Fact] public void BestCommonType_04() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_05() { var source = @"using System; class Program { static int M1(string s) => s.Length; static int M2(string s) => int.Parse(s); static void Main() { var a1 = new[] { M1, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => s.Length, M2 }; Report(a1[1]); Report(a2[1]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { M1, (string s) => int.Parse(s) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { M1, (string s) => int.Parse(s) }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (string s) => s.Length, M2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (string s) => s.Length, M2 }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_06() { var source = @"using System; class Program { static void F1<T>(T t) { } static T F2<T>() => default; static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object>, F2<string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object>, F2<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object>, F2<string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Func`1[System.Object]"); } [Fact] public void BestCommonType_07() { var source = @"class Program { static void F1<T>(T t) { } static T F2<T>() => default; static T F3<T>(T t) => t; static void Main() { var a1 = new[] { F1<int>, F1<object> }; var a2 = new[] { F2<nint>, F2<System.IntPtr> }; var a3 = new[] { F3<string>, F3<object> }; } }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<int>, F1<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<int>, F1<object> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<nint>, F2<System.IntPtr> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<nint>, F2<System.IntPtr> }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F3<string>, F3<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F3<string>, F3<object> }").WithLocation(10, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_08() { var source = @"#nullable enable using System; class Program { static void F<T>(T t) { } static void Main() { var a1 = new[] { F<string?>, F<string> }; var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<string?>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<string?>, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<(int X, object Y)>, F<(int, dynamic)> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Action`1[System.ValueTuple`2[System.Int32,System.Object]]"); } [Fact] public void BestCommonType_09() { var source = @"using System; class Program { static void Main() { var a1 = new[] { (object o) => { }, (string s) => { } }; var a2 = new[] { () => (object)null, () => (string)null }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object o) => { }, (string s) => { } }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { () => (object)null, () => (string)null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => (object)null, () => (string)null }").WithLocation(7, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,26): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(6, 26), // (6,34): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(6, 34)); } [Fact] public void BestCommonType_10() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<string>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<string>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<string>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000004}`2[System.String,System.Object] <>A{00000001}`2[System.Object,System.String]"); } [Fact] [WorkItem(55909, "https://github.com/dotnet/roslyn/issues/55909")] public void BestCommonType_11() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, object> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, object> }").WithLocation(9, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/55909: ConversionsBase.HasImplicitSignatureConversion() // relies on the variance of FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_12() { var source = @"class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, F<string> }; var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; } }"; var expectedDiagnostics = new[] { // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, F<string> }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_13() { var source = @"using System; class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, null }; var a2 = new[] { default, F<string> }; var a3 = new[] { null, default, (object x, ref string y) => { } }; Report(a1[0]); Report(a2[1]); Report(a3[2]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, null }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { default, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { default, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { null, default, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null, default, (object x, ref string y) => { } }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000001}`1[System.Object] <>A{00000001}`1[System.String] <>A{00000004}`2[System.Object,System.String] "); } /// <summary> /// Best common type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void BestCommonType_NoInferredSignature() { var source = @"class Program { static void F1() { } static int F1(int i) => i; static void F2() { } static void Main() { var a1 = new[] { F1 }; var a2 = new[] { F1, F2 }; var a3 = new[] { F2, F1 }; var a4 = new[] { x => x }; var a5 = new[] { x => x, (int y) => y }; var a6 = new[] { (int y) => y, static x => x }; var a7 = new[] { x => x, F1 }; var a8 = new[] { F1, (int y) => y }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F1, F2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, F2 }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F2, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2, F1 }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var a5 = new[] { x => x, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, (int y) => y }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var a6 = new[] { (int y) => y, static x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (int y) => y, static x => x }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var a8 = new[] { F1, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, (int y) => y }").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18)); } [Fact] public void ArrayInitializer_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Func<int>[] { () => 1 }; var a2 = new Expression<Func<int>>[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void ArrayInitializer_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Delegate[] { () => 1 }; var a2 = new Expression[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,35): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var a1 = new Delegate[] { () => 1 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 35), // (8,37): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // var a2 = new Expression[] { () => 2 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(8, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"); } [Fact] public void ArrayInitializer_03() { var source = @"using System; class Program { static void Main() { var a1 = new[] { () => 1 }; Report(a1[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { () => 1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => 1 }").WithLocation(6, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32]"); } [Fact] public void ConditionalOperator_01() { var source = @"class Program { static void F<T>(T t) { } static void Main() { var c1 = F<object> ?? F<string>; var c2 = ((object o) => { }) ?? ((string s) => { }); var c3 = F<string> ?? ((object o) => { }); } }"; var expectedDiagnostics = new[] { // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // var c1 = F<object> ?? F<string>; Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<object> ?? F<string>").WithArguments("??", "method group", "method group").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'lambda expression' and 'lambda expression' // var c2 = ((object o) => { }) ?? ((string s) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "((object o) => { }) ?? ((string s) => { })").WithArguments("??", "lambda expression", "lambda expression").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'lambda expression' // var c3 = F<string> ?? ((object o) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<string> ?? ((object o) => { })").WithArguments("??", "method group", "lambda expression").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaReturn_01() { var source = @"using System; class Program { static void Main() { var a1 = () => () => 1; var a2 = () => Main; Report(a1()); Report(a2()); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32] System.Action"); } [Fact] public void InferredType_MethodGroup() { var source = @"class Program { static void Main() { System.Delegate d = Main; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Fact] public void InferredType_LambdaExpression() { var source = @"class Program { static void Main() { System.Delegate d = () => { }; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_01() { var source = @"using System; class Program { static void Main() { Report(() => { return; }); Report((bool b) => { if (b) return; }); Report((bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action`1[System.Boolean] System.Action`1[System.Boolean] "); } [Fact] public void InferredReturnType_02() { var source = @"using System; class Program { static void Main() { Report(async () => { return; }); Report(async (bool b) => { if (b) return; }); Report(async (bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] "); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_03() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return null; }); Report((bool b) => { if (b) return; else return null; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return null; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return null; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_04() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return default; }); Report((bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return default; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return default; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [Fact] public void ExplicitReturnType_01() { var source = @"using System; class Program { static void Main() { Report(object () => { return; }); Report(object (bool b) => { if (b) return null; }); Report(object (bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,31): error CS0126: An object of a type convertible to 'object' is required // Report(object () => { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(6, 31), // (7,32): error CS1643: Not all code paths return a value in lambda expression of type 'Func<bool, object>' // Report(object (bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<bool, object>").WithLocation(7, 32), // (8,44): error CS0126: An object of a type convertible to 'object' is required // Report(object (bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(8, 44)); } [Fact] public void TypeInference_Constraints_01() { var source = @"using System; using System.Linq.Expressions; class Program { static T F1<T>(T t) where T : Delegate => t; static T F2<T>(T t) where T : Expression => t; static void Main() { Report(F1((int i) => { })); Report(F2(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((int i) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F2<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Action`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_02() { var source = @"using System; using System.Linq.Expressions; class A<T> { public static U F<U>(U u) where U : T => u; } class B { static void Main() { Report(A<object>.F(() => 1)); Report(A<ICloneable>.F(() => 1)); Report(A<Delegate>.F(() => 1)); Report(A<MulticastDelegate>.F(() => 1)); Report(A<Func<int>>.F(() => 1)); Report(A<Expression>.F(() => 1)); Report(A<LambdaExpression>.F(() => 1)); Report(A<Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_03() { var source = @"using System; using System.Linq.Expressions; class A<T, U> where U : T { public static V F<V>(V v) where V : U => v; } class B { static void Main() { Report(A<object, object>.F(() => 1)); Report(A<object, Delegate>.F(() => 1)); Report(A<object, Func<int>>.F(() => 1)); Report(A<Delegate, Func<int>>.F(() => 1)); Report(A<object, Expression>.F(() => 1)); Report(A<object, Expression<Func<int>>>.F(() => 1)); Report(A<Expression, LambdaExpression>.F(() => 1)); Report(A<Expression, Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_MatchingSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(string s) => s.Length; static void F2(string s) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_DistinctSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(object o) => o.GetHashCode(); static void F2(object o) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static T M<T>(T x, T y) => x; static int F1(int i) => i; static void F1() { } static T F2<T>(T t) => t; static void Main() { var f1 = M(x => x, (int y) => y); var f2 = M(F1, F2<int>); var f3 = M(F2<object>, z => z); Report(f1); Report(f2); Report(f3); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(F1, F2<int>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M(F2<object>, z => z); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(12, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Object,System.Object] "); } [Fact] public void TypeInference_02() { var source = @"using System; class Program { static T M<T>(T x, T y) where T : class => x ?? y; static T F<T>() => default; static void Main() { var f1 = M(F<object>, null); var f2 = M(default, F<string>); var f3 = M((object x, ref string y) => { }, default); var f4 = M(null, (ref object x, string y) => { }); Report(f1); Report(f2); Report(f3); Report(f4); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(F<object>, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(8, 18), // (9,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(default, F<string>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(9, 18), // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M((object x, ref string y) => { }, default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f4 = M(null, (ref object x, string y) => { }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Object] System.Func`1[System.String] <>A{00000004}`2[System.Object,System.String] <>A{00000001}`2[System.Object,System.String] "); } [Fact] public void TypeInference_LowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (string s) => { })); Report(F(() => 2, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (object o) => { })); Report(F(() => 1.0, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (11,22): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(11, 22), // (11,30): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(11, 30), // (12,24): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(12, 24), // (12,24): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("lambda expression").WithLocation(12, 24) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_02() { var source = @"using System; class Program { static T F<T>(T x, T y) => y; static void Main() { Report(F((string s) => { }, (object o) => { })); Report(F(() => string.Empty, () => new object())); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(7, 16), // (8,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(() => string.Empty, () => new object())); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(8, 16)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(7, 37), // (7,45): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(7, 45)); } [Fact] public void TypeInference_UpperAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<int>> a2 = null; Report(F1(a1, (string s) => { })); Report(F2(() => 2, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<object>> a2 = null; Report(F1(a1, (object o) => { })); Report(F2(() => string.Empty, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,23): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 23), // (12,31): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 31) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,42): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(10, 50) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F1(ref d1, (string s) => { })); Report(F2(() => 2, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<object> d2 = () => new object(); Report(F1(ref d1, (object o) => { })); Report(F2(() => string.Empty, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,27): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 27), // (12,35): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 35) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(in T x, T y) => y; static T F2<T>(T x, in T y) => y; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,16): error CS0411: The type arguments for method 'Program.F1<T>(in T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(in T, T)").WithLocation(10, 16), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): error CS1661: Cannot convert lambda expression to type 'Action<D1<string>>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<D1<string>>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'D1<string>' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "D1<string>").WithLocation(10, 50), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16)); } [Fact] public void TypeInference_Nested_01() { var source = @"delegate void D<T>(T t); class Program { static T F1<T>(T t) => t; static D<T> F2<T>(D<T> d) => d; static void Main() { F2(F1((string s) => { })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(D<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(D<T>)").WithLocation(8, 9)); } [Fact] public void TypeInference_Nested_02() { var source = @"using System.Linq.Expressions; class Program { static T F1<T>(T x) => throw null; static Expression<T> F2<T>(Expression<T> e) => e; static void Main() { F2(F1((object x1) => 1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((object x1) => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<T>)").WithLocation(8, 9)); } /// <summary> /// Method type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void TypeInference_NoInferredSignature() { var source = @"class Program { static void F1() { } static void F1(int i) { } static void F2() { } static T M1<T>(T t) => t; static T M2<T>(T x, T y) => x; static void Main() { var a1 = M1(F1); var a2 = M2(F1, F2); var a3 = M2(F2, F1); var a4 = M1(x => x); var a5 = M2(x => x, (int y) => y); var a6 = M2((int y) => y, x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a2 = M2(F1, F2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a3 = M2(F2, F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(12, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18), // (14,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a5 = M2(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(14, 18), // (15,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a6 = M2((int y) => y, x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18)); } [Fact] public void Variance() { var source = @"using System; delegate void StringAction(string s); class Program { static void Main() { Action<string> a1 = s => { }; Action<string> a2 = (string s) => { }; Action<string> a3 = (object o) => { }; Action<string> a4 = (Action<object>)((object o) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,29): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(9, 29), // (9,37): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(9, 37)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } [Fact] public void BinaryOperator_01() { var source = @"using System; class Program { static void Main() { var b1 = (() => { }) == null; var b2 = null == Main; var b3 = Main == (() => { }); Console.WriteLine((b1, b2, b3)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and '<null>' // var b1 = (() => { }) == null; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => { }) == null").WithArguments("==", "lambda expression", "<null>").WithLocation(6, 18), // (7,18): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // var b2 = null == Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == Main").WithArguments("==", "<null>", "method group").WithLocation(7, 18), // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'lambda expression' // var b3 = Main == (() => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main == (() => { })").WithArguments("==", "method group", "lambda expression").WithLocation(8, 18)); var expectedOutput = @"(False, False, False)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_02() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Expression e) { Console.WriteLine(""operator=(C c, Expression e)""); return c; } static void Main() { var c = new C(); _ = c + Main; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (10,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_03() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_04() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13), // (12,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_05() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_06() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static void Main() { var c = new C(); _ = c + (() => new object()); _ = c + (() => 1); } }"; var expectedOutput = @"operator+(C c, Func<object> f) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_07() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_08() { var source = @"using System; class A { public static A operator+(A a, Func<int> f) { Console.WriteLine(""operator+(A a, Func<int> f)""); return a; } } class B : A { public static B operator+(B b, Delegate d) { Console.WriteLine(""operator+(B b, Delegate d)""); return b; } static int F() => 1; static void Main() { var b = new B(); _ = b + F; _ = b + (() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"operator+(A a, Func<int> f) operator+(A a, Func<int> f) "); // Breaking change from C#9. string expectedOutput = @"operator+(B b, Delegate d) operator+(B b, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_18() { var source = @"using System; class Program { static void Main() { Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { return 1; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, out int _17) => { _17 = 0; return 2; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, ref int _17) => { return 3; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, in int _17) => { return 4; }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>F`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{200000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{100000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{300000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_19() { var source = @"using System; class Program { static void F1(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18) { } static void F2(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, out object _18) { _18 = null; } static void F3(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, ref object _18) { } static void F4(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, in object _18) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{800000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{400000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{c00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_20() { var source = @"using System; class Program { static void F1( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, int _33) { } static void F2( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, out int _33) { _33 = 0; } static void F3( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, ref int _33) { } static void F4( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, in int _33) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{4000000000000000\,00000000}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000002}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000001}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000003}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] "); } /// <summary> /// Synthesized delegate types should only be emitted if used. /// </summary> [Fact] [WorkItem(55896, "https://github.com/dotnet/roslyn/issues/55896")] public void SynthesizedDelegateTypes_21() { var source = @"using System; delegate void D2(object x, ref object y); delegate void D4(out object x, ref object y); class Program { static void F1(ref object x, object y) { } static void F2(object x, ref object y) { } static void Main() { var d1 = F1; D2 d2 = F2; var d3 = (ref object x, out object y) => { y = null; }; D4 d4 = (out object x, ref object y) => { x = null; }; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, validator: validator, expectedOutput: @"<>A{00000001}`2[System.Object,System.Object] D2 <>A{00000009}`2[System.Object,System.Object] D4"); static void validator(PEAssembly assembly) { var reader = assembly.GetMetadataReader(); var actualTypes = reader.GetTypeDefNames().Select(h => reader.GetString(h)).ToArray(); // https://github.com/dotnet/roslyn/issues/55896: Should not include <>A{00000004}`2 or <>A{00000006}`2. string[] expectedTypes = new[] { "<Module>", "<>A{00000001}`2", "<>A{00000004}`2", "<>A{00000006}`2", "<>A{00000009}`2", "D2", "D4", "Program", "<>c", }; AssertEx.Equal(expectedTypes, actualTypes); } } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Lowering/InitializerRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static class InitializerRewriter { internal static BoundTypeOrInstanceInitializers RewriteConstructor(ImmutableArray<BoundInitializer> boundInitializers, MethodSymbol method) { Debug.Assert(!boundInitializers.IsDefault); Debug.Assert((method.MethodKind == MethodKind.Constructor) || (method.MethodKind == MethodKind.StaticConstructor)); var sourceMethod = method as SourceMemberMethodSymbol; var syntax = ((object)sourceMethod != null) ? sourceMethod.SyntaxNode : method.GetNonNullSyntaxNode(); return new BoundTypeOrInstanceInitializers(syntax, boundInitializers.SelectAsArray(RewriteInitializersAsStatements)); } internal static BoundTypeOrInstanceInitializers RewriteScriptInitializer(ImmutableArray<BoundInitializer> boundInitializers, SynthesizedInteractiveInitializerMethod method, out bool hasTrailingExpression) { Debug.Assert(!boundInitializers.IsDefault); var boundStatements = ArrayBuilder<BoundStatement>.GetInstance(boundInitializers.Length); var submissionResultType = method.ResultType; var hasSubmissionResultType = (object)submissionResultType != null; BoundStatement lastStatement = null; BoundExpression trailingExpression = null; foreach (var initializer in boundInitializers) { // The value of the last expression statement (if any) is returned from the submission initializer, // unless this is a #load'ed tree. I the #load'ed tree case, we'll execute the trailing expression // but discard its result. if (hasSubmissionResultType && (initializer == boundInitializers.Last()) && (initializer.Kind == BoundKind.GlobalStatementInitializer) && method.DeclaringCompilation.IsSubmissionSyntaxTree(initializer.SyntaxTree)) { lastStatement = ((BoundGlobalStatementInitializer)initializer).Statement; var expression = GetTrailingScriptExpression(lastStatement); if (expression != null && (object)expression.Type != null && !expression.Type.IsVoidType()) { trailingExpression = expression; continue; } } boundStatements.Add(RewriteInitializersAsStatements(initializer)); } if (hasSubmissionResultType && (trailingExpression != null)) { Debug.Assert(!submissionResultType.IsVoidType()); // Note: The trailing expression was already converted to the submission result type in Binder.BindGlobalStatement. boundStatements.Add(new BoundReturnStatement(lastStatement.Syntax, RefKind.None, trailingExpression)); hasTrailingExpression = true; } else { hasTrailingExpression = false; } return new BoundTypeOrInstanceInitializers(method.GetNonNullSyntaxNode(), boundStatements.ToImmutableAndFree()); } /// <summary> /// Returns the expression if the statement is actually an expression (ExpressionStatementSyntax with no trailing semicolon). /// </summary> internal static BoundExpression GetTrailingScriptExpression(BoundStatement statement) { return (statement.Kind == BoundKind.ExpressionStatement) && ((ExpressionStatementSyntax)statement.Syntax).SemicolonToken.IsMissing ? ((BoundExpressionStatement)statement).Expression : null; } private static BoundStatement RewriteFieldInitializer(BoundFieldEqualsValue fieldInit) { SyntaxNode syntax = fieldInit.Syntax; syntax = (syntax as EqualsValueClauseSyntax)?.Value ?? syntax; //we want the attached sequence point to indicate the value node var boundReceiver = fieldInit.Field.IsStatic ? null : new BoundThisReference(syntax, fieldInit.Field.ContainingType); BoundStatement boundStatement = new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, boundReceiver, fieldInit.Field, constantValueOpt: null), fieldInit.Value, fieldInit.Field.Type) { WasCompilerGenerated = true }) { WasCompilerGenerated = !fieldInit.Locals.IsEmpty || fieldInit.WasCompilerGenerated }; if (!fieldInit.Locals.IsEmpty) { boundStatement = new BoundBlock(syntax, fieldInit.Locals, ImmutableArray.Create(boundStatement)) { WasCompilerGenerated = fieldInit.WasCompilerGenerated }; } Debug.Assert(LocalRewriter.IsFieldOrPropertyInitializer(boundStatement)); return boundStatement; } private static BoundStatement RewriteInitializersAsStatements(BoundInitializer initializer) { switch (initializer.Kind) { case BoundKind.FieldEqualsValue: return RewriteFieldInitializer((BoundFieldEqualsValue)initializer); case BoundKind.GlobalStatementInitializer: return ((BoundGlobalStatementInitializer)initializer).Statement; default: throw ExceptionUtilities.UnexpectedValue(initializer.Kind); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static class InitializerRewriter { internal static BoundTypeOrInstanceInitializers RewriteConstructor(ImmutableArray<BoundInitializer> boundInitializers, MethodSymbol method) { Debug.Assert(!boundInitializers.IsDefault); Debug.Assert((method.MethodKind == MethodKind.Constructor) || (method.MethodKind == MethodKind.StaticConstructor)); var sourceMethod = method as SourceMemberMethodSymbol; var syntax = ((object)sourceMethod != null) ? sourceMethod.SyntaxNode : method.GetNonNullSyntaxNode(); return new BoundTypeOrInstanceInitializers(syntax, boundInitializers.SelectAsArray(RewriteInitializersAsStatements)); } internal static BoundTypeOrInstanceInitializers RewriteScriptInitializer(ImmutableArray<BoundInitializer> boundInitializers, SynthesizedInteractiveInitializerMethod method, out bool hasTrailingExpression) { Debug.Assert(!boundInitializers.IsDefault); var boundStatements = ArrayBuilder<BoundStatement>.GetInstance(boundInitializers.Length); var submissionResultType = method.ResultType; var hasSubmissionResultType = (object)submissionResultType != null; BoundStatement lastStatement = null; BoundExpression trailingExpression = null; foreach (var initializer in boundInitializers) { // The value of the last expression statement (if any) is returned from the submission initializer, // unless this is a #load'ed tree. I the #load'ed tree case, we'll execute the trailing expression // but discard its result. if (hasSubmissionResultType && (initializer == boundInitializers.Last()) && (initializer.Kind == BoundKind.GlobalStatementInitializer) && method.DeclaringCompilation.IsSubmissionSyntaxTree(initializer.SyntaxTree)) { lastStatement = ((BoundGlobalStatementInitializer)initializer).Statement; var expression = GetTrailingScriptExpression(lastStatement); if (expression != null && (object)expression.Type != null && !expression.Type.IsVoidType()) { trailingExpression = expression; continue; } } boundStatements.Add(RewriteInitializersAsStatements(initializer)); } if (hasSubmissionResultType && (trailingExpression != null)) { Debug.Assert(!submissionResultType.IsVoidType()); // Note: The trailing expression was already converted to the submission result type in Binder.BindGlobalStatement. boundStatements.Add(new BoundReturnStatement(lastStatement.Syntax, RefKind.None, trailingExpression)); hasTrailingExpression = true; } else { hasTrailingExpression = false; } return new BoundTypeOrInstanceInitializers(method.GetNonNullSyntaxNode(), boundStatements.ToImmutableAndFree()); } /// <summary> /// Returns the expression if the statement is actually an expression (ExpressionStatementSyntax with no trailing semicolon). /// </summary> internal static BoundExpression GetTrailingScriptExpression(BoundStatement statement) { return (statement.Kind == BoundKind.ExpressionStatement) && ((ExpressionStatementSyntax)statement.Syntax).SemicolonToken.IsMissing ? ((BoundExpressionStatement)statement).Expression : null; } private static BoundStatement RewriteFieldInitializer(BoundFieldEqualsValue fieldInit) { SyntaxNode syntax = fieldInit.Syntax; syntax = (syntax as EqualsValueClauseSyntax)?.Value ?? syntax; //we want the attached sequence point to indicate the value node var boundReceiver = fieldInit.Field.IsStatic ? null : new BoundThisReference(syntax, fieldInit.Field.ContainingType); BoundStatement boundStatement = new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, boundReceiver, fieldInit.Field, constantValueOpt: null), fieldInit.Value, fieldInit.Field.Type) { WasCompilerGenerated = true }) { WasCompilerGenerated = !fieldInit.Locals.IsEmpty || fieldInit.WasCompilerGenerated }; if (!fieldInit.Locals.IsEmpty) { boundStatement = new BoundBlock(syntax, fieldInit.Locals, ImmutableArray.Create(boundStatement)) { WasCompilerGenerated = fieldInit.WasCompilerGenerated }; } Debug.Assert(LocalRewriter.IsFieldOrPropertyInitializer(boundStatement)); return boundStatement; } private static BoundStatement RewriteInitializersAsStatements(BoundInitializer initializer) { switch (initializer.Kind) { case BoundKind.FieldEqualsValue: return RewriteFieldInitializer((BoundFieldEqualsValue)initializer); case BoundKind.GlobalStatementInitializer: return ((BoundGlobalStatementInitializer)initializer).Statement; default: throw ExceptionUtilities.UnexpectedValue(initializer.Kind); } } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Core/Portable/Compilation/ControlFlowAnalysis.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides information about statements which transfer control in and out of a region. This /// information is returned from a call to <see cref="SemanticModel.AnalyzeControlFlow(SyntaxNode)" />. /// </summary> public abstract class ControlFlowAnalysis { /// <summary> /// The set of statements inside the region what are the /// destination of branches outside the region. /// </summary> public abstract ImmutableArray<SyntaxNode> EntryPoints { get; } /// <summary> /// The set of statements inside a region that jump to locations outside /// the region. /// </summary> public abstract ImmutableArray<SyntaxNode> ExitPoints { get; } /// <summary> /// Indicates whether a region completes normally. Return true if and only if the end of the /// last statement in a region is reachable or the region contains no statements. /// </summary> public abstract bool EndPointIsReachable { get; } public abstract bool StartPointIsReachable { get; } /// <summary> /// The set of return statements found within a region. /// </summary> public abstract ImmutableArray<SyntaxNode> ReturnStatements { get; } /// <summary> /// Returns true if and only if analysis was successful. Analysis can fail if the region does not properly span a single expression, /// a single statement, or a contiguous series of statements within the enclosing block. /// </summary> public abstract bool Succeeded { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides information about statements which transfer control in and out of a region. This /// information is returned from a call to <see cref="SemanticModel.AnalyzeControlFlow(SyntaxNode)" />. /// </summary> public abstract class ControlFlowAnalysis { /// <summary> /// The set of statements inside the region what are the /// destination of branches outside the region. /// </summary> public abstract ImmutableArray<SyntaxNode> EntryPoints { get; } /// <summary> /// The set of statements inside a region that jump to locations outside /// the region. /// </summary> public abstract ImmutableArray<SyntaxNode> ExitPoints { get; } /// <summary> /// Indicates whether a region completes normally. Return true if and only if the end of the /// last statement in a region is reachable or the region contains no statements. /// </summary> public abstract bool EndPointIsReachable { get; } public abstract bool StartPointIsReachable { get; } /// <summary> /// The set of return statements found within a region. /// </summary> public abstract ImmutableArray<SyntaxNode> ReturnStatements { get; } /// <summary> /// Returns true if and only if analysis was successful. Analysis can fail if the region does not properly span a single expression, /// a single statement, or a contiguous series of statements within the enclosing block. /// </summary> public abstract bool Succeeded { get; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticLineEnderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticLineEnderTests { protected abstract string Language { get; } protected abstract Action CreateNextHandler(TestWorkspace workspace); internal abstract IChainedCommandHandler<AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace); protected void Test(string expected, string markupCode, bool completionActive = false, bool assertNextHandlerInvoked = false) { TestFileMarkupParser.GetPositionsAndSpans(markupCode, out var code, out var positions, out _); Assert.NotEmpty(positions); foreach (var position in positions) { // Run the test once for each input position. All marked positions in the input for a test are expected // to have the same result. Test(expected, code, position, completionActive, assertNextHandlerInvoked); } } #pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/45892 private void Test(string expected, string code, int position, bool completionActive = false, bool assertNextHandlerInvoked = false) #pragma warning restore IDE0060 // Remove unused parameter { var markupCode = code[0..position] + "$$" + code[position..]; // WPF is required for some reason: https://github.com/dotnet/roslyn/issues/46286 using var workspace = TestWorkspace.Create(Language, compilationOptions: null, parseOptions: null, new[] { markupCode }, composition: EditorTestCompositions.EditorFeaturesWpf); var view = workspace.Documents.Single().GetTextView(); var buffer = workspace.Documents.Single().GetTextBuffer(); var nextHandlerInvoked = false; view.Caret.MoveTo(new SnapshotPoint(buffer.CurrentSnapshot, workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var nextHandler = assertNextHandlerInvoked ? () => nextHandlerInvoked = true : CreateNextHandler(workspace); commandHandler.ExecuteCommand(new AutomaticLineEnderCommandArgs(view, buffer), nextHandler, TestCommandExecutionContext.Create()); Test(view, buffer, expected); Assert.Equal(assertNextHandlerInvoked, nextHandlerInvoked); } private static void Test(ITextView view, ITextBuffer buffer, string expectedWithAnnotations) { MarkupTestFile.GetPosition(expectedWithAnnotations, out var expected, out int expectedPosition); // Remove any virtual space from the expected text. var virtualPosition = view.Caret.Position.VirtualBufferPosition; expected = expected.Remove(virtualPosition.Position, virtualPosition.VirtualSpaces); Assert.Equal(expected, buffer.CurrentSnapshot.GetText()); Assert.Equal(expectedPosition, virtualPosition.Position.Position + virtualPosition.VirtualSpaces); } public static T GetService<T>(TestWorkspace workspace) => workspace.GetService<T>(); public static T GetExportedValue<T>(TestWorkspace workspace) => workspace.ExportProvider.GetExportedValue<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; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticLineEnderTests { protected abstract string Language { get; } protected abstract Action CreateNextHandler(TestWorkspace workspace); internal abstract IChainedCommandHandler<AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace); protected void Test(string expected, string markupCode, bool completionActive = false, bool assertNextHandlerInvoked = false) { TestFileMarkupParser.GetPositionsAndSpans(markupCode, out var code, out var positions, out _); Assert.NotEmpty(positions); foreach (var position in positions) { // Run the test once for each input position. All marked positions in the input for a test are expected // to have the same result. Test(expected, code, position, completionActive, assertNextHandlerInvoked); } } #pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/45892 private void Test(string expected, string code, int position, bool completionActive = false, bool assertNextHandlerInvoked = false) #pragma warning restore IDE0060 // Remove unused parameter { var markupCode = code[0..position] + "$$" + code[position..]; // WPF is required for some reason: https://github.com/dotnet/roslyn/issues/46286 using var workspace = TestWorkspace.Create(Language, compilationOptions: null, parseOptions: null, new[] { markupCode }, composition: EditorTestCompositions.EditorFeaturesWpf); var view = workspace.Documents.Single().GetTextView(); var buffer = workspace.Documents.Single().GetTextBuffer(); var nextHandlerInvoked = false; view.Caret.MoveTo(new SnapshotPoint(buffer.CurrentSnapshot, workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var nextHandler = assertNextHandlerInvoked ? () => nextHandlerInvoked = true : CreateNextHandler(workspace); commandHandler.ExecuteCommand(new AutomaticLineEnderCommandArgs(view, buffer), nextHandler, TestCommandExecutionContext.Create()); Test(view, buffer, expected); Assert.Equal(assertNextHandlerInvoked, nextHandlerInvoked); } private static void Test(ITextView view, ITextBuffer buffer, string expectedWithAnnotations) { MarkupTestFile.GetPosition(expectedWithAnnotations, out var expected, out int expectedPosition); // Remove any virtual space from the expected text. var virtualPosition = view.Caret.Position.VirtualBufferPosition; expected = expected.Remove(virtualPosition.Position, virtualPosition.VirtualSpaces); Assert.Equal(expected, buffer.CurrentSnapshot.GetText()); Assert.Equal(expectedPosition, virtualPosition.Position.Position + virtualPosition.VirtualSpaces); } public static T GetService<T>(TestWorkspace workspace) => workspace.GetService<T>(); public static T GetExportedValue<T>(TestWorkspace workspace) => workspace.ExportProvider.GetExportedValue<T>(); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenInterpolatedString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class InterpolatedStringTests : CSharpTestBase { [Fact, WorkItem(33713, "https://github.com/dotnet/roslyn/issues/33713")] public void AlternateVerbatimString() { var source = @" class C { static void Main() { int i = 42; var s = @$""{i} {i}""; System.Console.Write(s); var s2 = $@""""; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"42 42"); var tree = comp.SyntaxTrees.Single(); var interpolatedStrings = tree.GetRoot().DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().ToArray(); var token1 = interpolatedStrings[0].StringStartToken; Assert.Equal("@$\"", token1.Text); Assert.Equal("@$\"", token1.ValueText); var token2 = interpolatedStrings[1].StringStartToken; Assert.Equal("$@\"", token2.Text); Assert.Equal("$@\"", token2.ValueText); foreach (var token in tree.GetRoot().DescendantTokens().Where(t => t.Kind() != SyntaxKind.EndOfFileToken)) { Assert.False(string.IsNullOrEmpty(token.Text)); Assert.False(string.IsNullOrEmpty(token.ValueText)); } } [Fact] public void ConstInterpolations() { var source = @" using System; public class Test { const string constantabc = ""abc""; const string constantnull = null; static void Main() { Console.WriteLine($""""); Console.WriteLine($""ABC""); Console.WriteLine($""{constantabc}""); Console.WriteLine($""{constantnull}""); Console.WriteLine($""{constantabc}{constantnull}""); Console.WriteLine($""({constantabc})({constantnull})""); } } "; var comp = CompileAndVerify(source, expectedOutput: @" ABC abc abc (abc)() "); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 61 (0x3d) .maxstack 1 IL_0000: ldstr """" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldstr ""ABC"" IL_000f: call ""void System.Console.WriteLine(string)"" IL_0014: ldstr ""abc"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ldstr """" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldstr ""abc"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldstr ""(abc)()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } "); } [Fact] public void InterpolatedStringIsNeverNull() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(M6(null) == """"); Console.WriteLine(M6(""abc"")); } static string M6(string a) => $""{a}""; } "; var comp = CompileAndVerify(source, expectedOutput: @"True abc "); comp.VerifyDiagnostics(); comp.VerifyIL("Test.M6", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000a IL_0004: pop IL_0005: ldstr """" IL_000a: ret } "); } [Fact] public void ConcatenatedStringInterpolations() { var source = @" using System; public class Test { static void Main() { string a = ""a""; string b = ""b""; Console.WriteLine($""a: {a}""); Console.WriteLine($""{a + b}""); Console.WriteLine($""{a}{b}""); Console.WriteLine($""a: {a}, b: {b}""); Console.WriteLine($""{{{a}}}""); Console.WriteLine(""a:"" + $"" {a}""); Console.WriteLine($""a: {$""{a}, b: {b}""}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"a: a ab ab a: a, b: b {a} a: a a: a, b: b "); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 134 (0x86) .maxstack 4 .locals init (string V_0, //a string V_1) //b IL_0000: ldstr ""a"" IL_0005: stloc.0 IL_0006: ldstr ""b"" IL_000b: stloc.1 IL_000c: ldstr ""a: "" IL_0011: ldloc.0 IL_0012: call ""string string.Concat(string, string)"" IL_0017: call ""void System.Console.WriteLine(string)"" IL_001c: ldloc.0 IL_001d: ldloc.1 IL_001e: call ""string string.Concat(string, string)"" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldloc.0 IL_0029: ldloc.1 IL_002a: call ""string string.Concat(string, string)"" IL_002f: call ""void System.Console.WriteLine(string)"" IL_0034: ldstr ""a: "" IL_0039: ldloc.0 IL_003a: ldstr "", b: "" IL_003f: ldloc.1 IL_0040: call ""string string.Concat(string, string, string, string)"" IL_0045: call ""void System.Console.WriteLine(string)"" IL_004a: ldstr ""{"" IL_004f: ldloc.0 IL_0050: ldstr ""}"" IL_0055: call ""string string.Concat(string, string, string)"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ldstr ""a: "" IL_0064: ldloc.0 IL_0065: call ""string string.Concat(string, string)"" IL_006a: call ""void System.Console.WriteLine(string)"" IL_006f: ldstr ""a: "" IL_0074: ldloc.0 IL_0075: ldstr "", b: "" IL_007a: ldloc.1 IL_007b: call ""string string.Concat(string, string, string, string)"" IL_0080: call ""void System.Console.WriteLine(string)"" IL_0085: ret } "); } [Fact] public void NonConcatenatedInterpolations() { var source = @" using System; public class Test { static void Main() { object a = ""a""; Console.WriteLine($""{a}""); Console.WriteLine($""a: {a}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"a a: a "); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 39 (0x27) .maxstack 2 .locals init (object V_0) //a IL_0000: ldstr ""a"" IL_0005: stloc.0 IL_0006: ldstr ""{0}"" IL_000b: ldloc.0 IL_000c: call ""string string.Format(string, object)"" IL_0011: call ""void System.Console.WriteLine(string)"" IL_0016: ldstr ""a: {0}"" IL_001b: ldloc.0 IL_001c: call ""string string.Format(string, object)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } "); } [Fact] public void ExpressionsAreNotOptimized() { var source = @" using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<string, string>> f = a => $""a: {a}""; Console.Write(f); } } "; var comp = CompileAndVerify(source, expectedOutput: @"a => Format(""a: {0}"", a)"); comp.VerifyDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class InterpolatedStringTests : CSharpTestBase { [Fact, WorkItem(33713, "https://github.com/dotnet/roslyn/issues/33713")] public void AlternateVerbatimString() { var source = @" class C { static void Main() { int i = 42; var s = @$""{i} {i}""; System.Console.Write(s); var s2 = $@""""; } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"42 42"); var tree = comp.SyntaxTrees.Single(); var interpolatedStrings = tree.GetRoot().DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().ToArray(); var token1 = interpolatedStrings[0].StringStartToken; Assert.Equal("@$\"", token1.Text); Assert.Equal("@$\"", token1.ValueText); var token2 = interpolatedStrings[1].StringStartToken; Assert.Equal("$@\"", token2.Text); Assert.Equal("$@\"", token2.ValueText); foreach (var token in tree.GetRoot().DescendantTokens().Where(t => t.Kind() != SyntaxKind.EndOfFileToken)) { Assert.False(string.IsNullOrEmpty(token.Text)); Assert.False(string.IsNullOrEmpty(token.ValueText)); } } [Fact] public void ConstInterpolations() { var source = @" using System; public class Test { const string constantabc = ""abc""; const string constantnull = null; static void Main() { Console.WriteLine($""""); Console.WriteLine($""ABC""); Console.WriteLine($""{constantabc}""); Console.WriteLine($""{constantnull}""); Console.WriteLine($""{constantabc}{constantnull}""); Console.WriteLine($""({constantabc})({constantnull})""); } } "; var comp = CompileAndVerify(source, expectedOutput: @" ABC abc abc (abc)() "); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 61 (0x3d) .maxstack 1 IL_0000: ldstr """" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldstr ""ABC"" IL_000f: call ""void System.Console.WriteLine(string)"" IL_0014: ldstr ""abc"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ldstr """" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldstr ""abc"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldstr ""(abc)()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } "); } [Fact] public void InterpolatedStringIsNeverNull() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(M6(null) == """"); Console.WriteLine(M6(""abc"")); } static string M6(string a) => $""{a}""; } "; var comp = CompileAndVerify(source, expectedOutput: @"True abc "); comp.VerifyDiagnostics(); comp.VerifyIL("Test.M6", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000a IL_0004: pop IL_0005: ldstr """" IL_000a: ret } "); } [Fact] public void ConcatenatedStringInterpolations() { var source = @" using System; public class Test { static void Main() { string a = ""a""; string b = ""b""; Console.WriteLine($""a: {a}""); Console.WriteLine($""{a + b}""); Console.WriteLine($""{a}{b}""); Console.WriteLine($""a: {a}, b: {b}""); Console.WriteLine($""{{{a}}}""); Console.WriteLine(""a:"" + $"" {a}""); Console.WriteLine($""a: {$""{a}, b: {b}""}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"a: a ab ab a: a, b: b {a} a: a a: a, b: b "); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 134 (0x86) .maxstack 4 .locals init (string V_0, //a string V_1) //b IL_0000: ldstr ""a"" IL_0005: stloc.0 IL_0006: ldstr ""b"" IL_000b: stloc.1 IL_000c: ldstr ""a: "" IL_0011: ldloc.0 IL_0012: call ""string string.Concat(string, string)"" IL_0017: call ""void System.Console.WriteLine(string)"" IL_001c: ldloc.0 IL_001d: ldloc.1 IL_001e: call ""string string.Concat(string, string)"" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldloc.0 IL_0029: ldloc.1 IL_002a: call ""string string.Concat(string, string)"" IL_002f: call ""void System.Console.WriteLine(string)"" IL_0034: ldstr ""a: "" IL_0039: ldloc.0 IL_003a: ldstr "", b: "" IL_003f: ldloc.1 IL_0040: call ""string string.Concat(string, string, string, string)"" IL_0045: call ""void System.Console.WriteLine(string)"" IL_004a: ldstr ""{"" IL_004f: ldloc.0 IL_0050: ldstr ""}"" IL_0055: call ""string string.Concat(string, string, string)"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ldstr ""a: "" IL_0064: ldloc.0 IL_0065: call ""string string.Concat(string, string)"" IL_006a: call ""void System.Console.WriteLine(string)"" IL_006f: ldstr ""a: "" IL_0074: ldloc.0 IL_0075: ldstr "", b: "" IL_007a: ldloc.1 IL_007b: call ""string string.Concat(string, string, string, string)"" IL_0080: call ""void System.Console.WriteLine(string)"" IL_0085: ret } "); } [Fact] public void NonConcatenatedInterpolations() { var source = @" using System; public class Test { static void Main() { object a = ""a""; Console.WriteLine($""{a}""); Console.WriteLine($""a: {a}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"a a: a "); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 39 (0x27) .maxstack 2 .locals init (object V_0) //a IL_0000: ldstr ""a"" IL_0005: stloc.0 IL_0006: ldstr ""{0}"" IL_000b: ldloc.0 IL_000c: call ""string string.Format(string, object)"" IL_0011: call ""void System.Console.WriteLine(string)"" IL_0016: ldstr ""a: {0}"" IL_001b: ldloc.0 IL_001c: call ""string string.Format(string, object)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } "); } [Fact] public void ExpressionsAreNotOptimized() { var source = @" using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<string, string>> f = a => $""a: {a}""; Console.Write(f); } } "; var comp = CompileAndVerify(source, expectedOutput: @"a => Format(""a: {0}"", a)"); comp.VerifyDiagnostics(); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Features/CSharp/Portable/CommentSelection/CSharpCommentSelectionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.CommentSelection { [ExportLanguageService(typeof(ICommentSelectionService), LanguageNames.CSharp), Shared] internal class CSharpCommentSelectionService : AbstractCommentSelectionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCommentSelectionService() { } public override string SingleLineCommentString => "//"; public override bool SupportsBlockComment => true; public override string BlockCommentStartString => "/*"; public override string BlockCommentEndString => "*/"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.CommentSelection { [ExportLanguageService(typeof(ICommentSelectionService), LanguageNames.CSharp), Shared] internal class CSharpCommentSelectionService : AbstractCommentSelectionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCommentSelectionService() { } public override string SingleLineCommentString => "//"; public override bool SupportsBlockComment => true; public override string BlockCommentStartString => "/*"; public override string BlockCommentEndString => "*/"; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/AbstractCodeRefactorDialog_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls.Primitives; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal abstract class AbstractCodeRefactorDialog_InProc<DialogType, AccessorType> : InProcComponent { public virtual void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { Thread.Yield(); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public virtual void VerifyClosed() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { return; } Thread.Yield(); } } } protected virtual async Task<DialogType> GetDialogAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); return Application.Current.Windows.OfType<DialogType>().Single(); } protected virtual async Task<DialogType> TryGetDialogAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); return Application.Current.Windows.OfType<DialogType>().SingleOrDefault(); } protected virtual async Task ClickAsync(Func<AccessorType, ButtonBase> buttonSelector, CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); var dialog = await GetDialogAsync(cancellationToken); var button = buttonSelector(GetAccessor(dialog)); var result = await button.SimulateClickAsync(JoinableTaskFactory); Contract.ThrowIfFalse(result); } protected abstract AccessorType GetAccessor(DialogType dialog); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls.Primitives; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal abstract class AbstractCodeRefactorDialog_InProc<DialogType, AccessorType> : InProcComponent { public virtual void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { Thread.Yield(); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public virtual void VerifyClosed() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { return; } Thread.Yield(); } } } protected virtual async Task<DialogType> GetDialogAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); return Application.Current.Windows.OfType<DialogType>().Single(); } protected virtual async Task<DialogType> TryGetDialogAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); return Application.Current.Windows.OfType<DialogType>().SingleOrDefault(); } protected virtual async Task ClickAsync(Func<AccessorType, ButtonBase> buttonSelector, CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); var dialog = await GetDialogAsync(cancellationToken); var button = buttonSelector(GetAccessor(dialog)); var result = await button.SimulateClickAsync(JoinableTaskFactory); Contract.ThrowIfFalse(result); } protected abstract AccessorType GetAccessor(DialogType dialog); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Features/Core/Portable/RQName/Nodes/RQArrayOrPointerType.cs
// Licensed to the .NET Foundation under one or more 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.Features.RQName.Nodes { internal abstract class RQArrayOrPointerType : RQType { public readonly RQType ElementType; public RQArrayOrPointerType(RQType elementType) => ElementType = elementType; } }
// Licensed to the .NET Foundation under one or more 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.Features.RQName.Nodes { internal abstract class RQArrayOrPointerType : RQType { public readonly RQType ElementType; public RQArrayOrPointerType(RQType elementType) => ElementType = elementType; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpFileBannerFactsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(IFileBannerFactsService), LanguageNames.CSharp), Shared] internal class CSharpFileBannerFactsService : CSharpFileBannerFacts, IFileBannerFactsService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFileBannerFactsService() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(IFileBannerFactsService), LanguageNames.CSharp), Shared] internal class CSharpFileBannerFactsService : CSharpFileBannerFacts, IFileBannerFactsService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFileBannerFactsService() { } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/BoundTree/BoundLocalDeclarationKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Indicates whether a bound local is also a declaration, and if so was it a declaration with an explicit or an inferred type. /// Ex: /// - In `M(x)`, `x` has `LocalDeclarationKind.None` /// - In `M(out int x)`, `x` has `LocalDeclarationKind.WithExplicitType` /// - In `M(out var x)`, `x` has `LocalDeclarationKind.WithInferredType` /// </summary> internal enum BoundLocalDeclarationKind { None = 0, WithExplicitType, WithInferredType } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Indicates whether a bound local is also a declaration, and if so was it a declaration with an explicit or an inferred type. /// Ex: /// - In `M(x)`, `x` has `LocalDeclarationKind.None` /// - In `M(out int x)`, `x` has `LocalDeclarationKind.WithExplicitType` /// - In `M(out var x)`, `x` has `LocalDeclarationKind.WithInferredType` /// </summary> internal enum BoundLocalDeclarationKind { None = 0, WithExplicitType, WithInferredType } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Parser/SlidingTextWindow.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { /// <summary> /// Keeps a sliding buffer over the SourceText of a file for the lexer. Also /// provides the lexer with the ability to keep track of a current "lexeme" /// by leaving a marker and advancing ahead the offset. The lexer can then /// decide to "keep" the lexeme by erasing the marker, or abandon the current /// lexeme by moving the offset back to the marker. /// </summary> internal sealed class SlidingTextWindow : IDisposable { /// <summary> /// In many cases, e.g. PeekChar, we need the ability to indicate that there are /// no characters left and we have reached the end of the stream, or some other /// invalid or not present character was asked for. Due to perf concerns, things /// like nullable or out variables are not viable. Instead we need to choose a /// char value which can never be legal. /// /// In .NET, all characters are represented in 16 bits using the UTF-16 encoding. /// Fortunately for us, there are a variety of different bit patterns which /// are *not* legal UTF-16 characters. 0xffff (char.MaxValue) is one of these /// characters -- a legal Unicode code point, but not a legal UTF-16 bit pattern. /// </summary> public const char InvalidCharacter = char.MaxValue; private const int DefaultWindowLength = 2048; private readonly SourceText _text; // Source of text to parse. private int _basis; // Offset of the window relative to the SourceText start. private int _offset; // Offset from the start of the window. private readonly int _textEnd; // Absolute end position private char[] _characterWindow; // Moveable window of chars from source text private int _characterWindowCount; // # of valid characters in chars buffer private int _lexemeStart; // Start of current lexeme relative to the window start. // Example for the above variables: // The text starts at 0. // The window onto the text starts at basis. // The current character is at (basis + offset), AKA the current "Position". // The current lexeme started at (basis + lexemeStart), which is <= (basis + offset) // The current lexeme is the characters between the lexemeStart and the offset. private readonly StringTable _strings; private static readonly ObjectPool<char[]> s_windowPool = new ObjectPool<char[]>(() => new char[DefaultWindowLength]); public SlidingTextWindow(SourceText text) { _text = text; _basis = 0; _offset = 0; _textEnd = text.Length; _strings = StringTable.GetInstance(); _characterWindow = s_windowPool.Allocate(); _lexemeStart = 0; } public void Dispose() { if (_characterWindow != null) { s_windowPool.Free(_characterWindow); _characterWindow = null; _strings.Free(); } } public SourceText Text => _text; /// <summary> /// The current absolute position in the text file. /// </summary> public int Position { get { return _basis + _offset; } } /// <summary> /// The current offset inside the window (relative to the window start). /// </summary> public int Offset { get { return _offset; } } /// <summary> /// The buffer backing the current window. /// </summary> public char[] CharacterWindow { get { return _characterWindow; } } /// <summary> /// Returns the start of the current lexeme relative to the window start. /// </summary> public int LexemeRelativeStart { get { return _lexemeStart; } } /// <summary> /// Number of characters in the character window. /// </summary> public int CharacterWindowCount { get { return _characterWindowCount; } } /// <summary> /// The absolute position of the start of the current lexeme in the given /// SourceText. /// </summary> public int LexemeStartPosition { get { return _basis + _lexemeStart; } } /// <summary> /// The number of characters in the current lexeme. /// </summary> public int Width { get { return _offset - _lexemeStart; } } /// <summary> /// Start parsing a new lexeme. /// </summary> public void Start() { _lexemeStart = _offset; } public void Reset(int position) { // if position is within already read character range then just use what we have int relative = position - _basis; if (relative >= 0 && relative <= _characterWindowCount) { _offset = relative; } else { // we need to reread text buffer int amountToRead = Math.Min(_text.Length, position + _characterWindow.Length) - position; amountToRead = Math.Max(amountToRead, 0); if (amountToRead > 0) { _text.CopyTo(position, _characterWindow, 0, amountToRead); } _lexemeStart = 0; _offset = 0; _basis = position; _characterWindowCount = amountToRead; } } private bool MoreChars() { if (_offset >= _characterWindowCount) { if (this.Position >= _textEnd) { return false; } // if lexeme scanning is sufficiently into the char buffer, // then refocus the window onto the lexeme if (_lexemeStart > (_characterWindowCount / 4)) { Array.Copy(_characterWindow, _lexemeStart, _characterWindow, 0, _characterWindowCount - _lexemeStart); _characterWindowCount -= _lexemeStart; _offset -= _lexemeStart; _basis += _lexemeStart; _lexemeStart = 0; } if (_characterWindowCount >= _characterWindow.Length) { // grow char array, since we need more contiguous space char[] oldWindow = _characterWindow; char[] newWindow = new char[_characterWindow.Length * 2]; Array.Copy(oldWindow, 0, newWindow, 0, _characterWindowCount); s_windowPool.ForgetTrackedObject(oldWindow, newWindow); _characterWindow = newWindow; } int amountToRead = Math.Min(_textEnd - (_basis + _characterWindowCount), _characterWindow.Length - _characterWindowCount); _text.CopyTo(_basis + _characterWindowCount, _characterWindow, _characterWindowCount, amountToRead); _characterWindowCount += amountToRead; return amountToRead > 0; } return true; } /// <summary> /// After reading <see cref=" InvalidCharacter"/>, a consumer can determine /// if the InvalidCharacter was in the user's source or a sentinel. /// /// Comments and string literals are allowed to contain any Unicode character. /// </summary> /// <returns></returns> internal bool IsReallyAtEnd() { return _offset >= _characterWindowCount && Position >= _textEnd; } /// <summary> /// Advance the current position by one. No guarantee that this /// position is valid. /// </summary> public void AdvanceChar() { _offset++; } /// <summary> /// Advance the current position by n. No guarantee that this position /// is valid. /// </summary> public void AdvanceChar(int n) { _offset += n; } /// <summary> /// Grab the next character and advance the position. /// </summary> /// <returns> /// The next character, <see cref="InvalidCharacter" /> if there were no characters /// remaining. /// </returns> public char NextChar() { char c = PeekChar(); if (c != InvalidCharacter) { this.AdvanceChar(); } return c; } /// <summary> /// Gets the next character if there are any characters in the /// SourceText. May advance the window if we are at the end. /// </summary> /// <returns> /// The next character if any are available. InvalidCharacter otherwise. /// </returns> public char PeekChar() { if (_offset >= _characterWindowCount && !MoreChars()) { return InvalidCharacter; } // N.B. MoreChars may update the offset. return _characterWindow[_offset]; } /// <summary> /// Gets the character at the given offset to the current position if /// the position is valid within the SourceText. /// </summary> /// <returns> /// The next character if any are available. InvalidCharacter otherwise. /// </returns> public char PeekChar(int delta) { int position = this.Position; this.AdvanceChar(delta); char ch; if (_offset >= _characterWindowCount && !MoreChars()) { ch = InvalidCharacter; } else { // N.B. MoreChars may update the offset. ch = _characterWindow[_offset]; } this.Reset(position); return ch; } public bool IsUnicodeEscape() { if (this.PeekChar() == '\\') { var ch2 = this.PeekChar(1); if (ch2 == 'U' || ch2 == 'u') { return true; } } return false; } public char PeekCharOrUnicodeEscape(out char surrogateCharacter) { if (this.IsUnicodeEscape()) { return this.PeekUnicodeEscape(out surrogateCharacter); } else { surrogateCharacter = InvalidCharacter; return this.PeekChar(); } } public char PeekUnicodeEscape(out char surrogateCharacter) { int position = this.Position; // if we're peeking, then we don't want to change the position SyntaxDiagnosticInfo info; var ch = this.ScanUnicodeEscape(peek: true, surrogateCharacter: out surrogateCharacter, info: out info); Debug.Assert(info == null, "Never produce a diagnostic while peeking."); this.Reset(position); return ch; } public char NextCharOrUnicodeEscape(out char surrogateCharacter, out SyntaxDiagnosticInfo info) { var ch = this.PeekChar(); Debug.Assert(ch != InvalidCharacter, "Precondition established by all callers; required for correctness of AdvanceChar() call."); if (ch == '\\') { var ch2 = this.PeekChar(1); if (ch2 == 'U' || ch2 == 'u') { return this.ScanUnicodeEscape(peek: false, surrogateCharacter: out surrogateCharacter, info: out info); } } surrogateCharacter = InvalidCharacter; info = null; this.AdvanceChar(); return ch; } public char NextUnicodeEscape(out char surrogateCharacter, out SyntaxDiagnosticInfo info) { return ScanUnicodeEscape(peek: false, surrogateCharacter: out surrogateCharacter, info: out info); } private char ScanUnicodeEscape(bool peek, out char surrogateCharacter, out SyntaxDiagnosticInfo info) { surrogateCharacter = InvalidCharacter; info = null; int start = this.Position; char character = this.PeekChar(); Debug.Assert(character == '\\'); this.AdvanceChar(); character = this.PeekChar(); if (character == 'U') { uint uintChar = 0; this.AdvanceChar(); if (!SyntaxFacts.IsHexDigit(this.PeekChar())) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { for (int i = 0; i < 8; i++) { character = this.PeekChar(); if (!SyntaxFacts.IsHexDigit(character)) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } break; } uintChar = (uint)((uintChar << 4) + SyntaxFacts.HexValue(character)); this.AdvanceChar(); } if (uintChar > 0x0010FFFF) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { character = GetCharsFromUtf32(uintChar, out surrogateCharacter); } } } else { Debug.Assert(character == 'u' || character == 'x'); int intChar = 0; this.AdvanceChar(); if (!SyntaxFacts.IsHexDigit(this.PeekChar())) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { for (int i = 0; i < 4; i++) { char ch2 = this.PeekChar(); if (!SyntaxFacts.IsHexDigit(ch2)) { if (character == 'u') { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } break; } intChar = (intChar << 4) + SyntaxFacts.HexValue(ch2); this.AdvanceChar(); } character = (char)intChar; } } return character; } /// <summary> /// Given that the next character is an ampersand ('&amp;'), attempt to interpret the /// following characters as an XML entity. On success, populate the out parameters /// with the low and high UTF-16 surrogates for the character represented by the /// entity. /// </summary> /// <param name="ch">e.g. '&lt;' for &amp;lt;.</param> /// <param name="surrogate">e.g. '\uDC00' for &amp;#x10000; (ch == '\uD800').</param> /// <returns>True if a valid XML entity was consumed.</returns> /// <remarks> /// NOTE: Always advances, even on failure. /// </remarks> public bool TryScanXmlEntity(out char ch, out char surrogate) { Debug.Assert(this.PeekChar() == '&'); ch = '&'; this.AdvanceChar(); surrogate = InvalidCharacter; switch (this.PeekChar()) { case 'l': if (AdvanceIfMatches("lt;")) { ch = '<'; return true; } break; case 'g': if (AdvanceIfMatches("gt;")) { ch = '>'; return true; } break; case 'a': if (AdvanceIfMatches("amp;")) { ch = '&'; return true; } else if (AdvanceIfMatches("apos;")) { ch = '\''; return true; } break; case 'q': if (AdvanceIfMatches("quot;")) { ch = '"'; return true; } break; case '#': { this.AdvanceChar(); //# uint uintChar = 0; if (AdvanceIfMatches("x")) { char digit; while (SyntaxFacts.IsHexDigit(digit = this.PeekChar())) { this.AdvanceChar(); // disallow overflow if (uintChar <= 0x7FFFFFF) { uintChar = (uintChar << 4) + (uint)SyntaxFacts.HexValue(digit); } else { return false; } } } else { char digit; while (SyntaxFacts.IsDecDigit(digit = this.PeekChar())) { this.AdvanceChar(); // disallow overflow if (uintChar <= 0x7FFFFFF) { uintChar = (uintChar << 3) + (uintChar << 1) + (uint)SyntaxFacts.DecValue(digit); } else { return false; } } } if (AdvanceIfMatches(";")) { ch = GetCharsFromUtf32(uintChar, out surrogate); return true; } break; } } return false; } /// <summary> /// If the next characters in the window match the given string, /// then advance past those characters. Otherwise, do nothing. /// </summary> private bool AdvanceIfMatches(string desired) { int length = desired.Length; for (int i = 0; i < length; i++) { if (PeekChar(i) != desired[i]) { return false; } } AdvanceChar(length); return true; } private SyntaxDiagnosticInfo CreateIllegalEscapeDiagnostic(int start) { return new SyntaxDiagnosticInfo(start - this.LexemeStartPosition, this.Position - start, ErrorCode.ERR_IllegalEscape); } public string Intern(StringBuilder text) { return _strings.Add(text); } public string Intern(char[] array, int start, int length) { return _strings.Add(array, start, length); } public string GetInternedText() { return this.Intern(_characterWindow, _lexemeStart, this.Width); } public string GetText(bool intern) { return this.GetText(this.LexemeStartPosition, this.Width, intern); } public string GetText(int position, int length, bool intern) { int offset = position - _basis; // PERF: Whether interning or not, there are some frequently occurring // easy cases we can pick off easily. switch (length) { case 0: return string.Empty; case 1: if (_characterWindow[offset] == ' ') { return " "; } if (_characterWindow[offset] == '\n') { return "\n"; } break; case 2: char firstChar = _characterWindow[offset]; if (firstChar == '\r' && _characterWindow[offset + 1] == '\n') { return "\r\n"; } if (firstChar == '/' && _characterWindow[offset + 1] == '/') { return "//"; } break; case 3: if (_characterWindow[offset] == '/' && _characterWindow[offset + 1] == '/' && _characterWindow[offset + 2] == ' ') { return "// "; } break; } if (intern) { return this.Intern(_characterWindow, offset, length); } else { return new string(_characterWindow, offset, length); } } internal static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate) { if (codepoint < (uint)0x00010000) { lowSurrogate = InvalidCharacter; return (char)codepoint; } else { Debug.Assert(codepoint > 0x0000FFFF && codepoint <= 0x0010FFFF); lowSurrogate = (char)((codepoint - 0x00010000) % 0x0400 + 0xDC00); return (char)((codepoint - 0x00010000) / 0x0400 + 0xD800); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { /// <summary> /// Keeps a sliding buffer over the SourceText of a file for the lexer. Also /// provides the lexer with the ability to keep track of a current "lexeme" /// by leaving a marker and advancing ahead the offset. The lexer can then /// decide to "keep" the lexeme by erasing the marker, or abandon the current /// lexeme by moving the offset back to the marker. /// </summary> internal sealed class SlidingTextWindow : IDisposable { /// <summary> /// In many cases, e.g. PeekChar, we need the ability to indicate that there are /// no characters left and we have reached the end of the stream, or some other /// invalid or not present character was asked for. Due to perf concerns, things /// like nullable or out variables are not viable. Instead we need to choose a /// char value which can never be legal. /// /// In .NET, all characters are represented in 16 bits using the UTF-16 encoding. /// Fortunately for us, there are a variety of different bit patterns which /// are *not* legal UTF-16 characters. 0xffff (char.MaxValue) is one of these /// characters -- a legal Unicode code point, but not a legal UTF-16 bit pattern. /// </summary> public const char InvalidCharacter = char.MaxValue; private const int DefaultWindowLength = 2048; private readonly SourceText _text; // Source of text to parse. private int _basis; // Offset of the window relative to the SourceText start. private int _offset; // Offset from the start of the window. private readonly int _textEnd; // Absolute end position private char[] _characterWindow; // Moveable window of chars from source text private int _characterWindowCount; // # of valid characters in chars buffer private int _lexemeStart; // Start of current lexeme relative to the window start. // Example for the above variables: // The text starts at 0. // The window onto the text starts at basis. // The current character is at (basis + offset), AKA the current "Position". // The current lexeme started at (basis + lexemeStart), which is <= (basis + offset) // The current lexeme is the characters between the lexemeStart and the offset. private readonly StringTable _strings; private static readonly ObjectPool<char[]> s_windowPool = new ObjectPool<char[]>(() => new char[DefaultWindowLength]); public SlidingTextWindow(SourceText text) { _text = text; _basis = 0; _offset = 0; _textEnd = text.Length; _strings = StringTable.GetInstance(); _characterWindow = s_windowPool.Allocate(); _lexemeStart = 0; } public void Dispose() { if (_characterWindow != null) { s_windowPool.Free(_characterWindow); _characterWindow = null; _strings.Free(); } } public SourceText Text => _text; /// <summary> /// The current absolute position in the text file. /// </summary> public int Position { get { return _basis + _offset; } } /// <summary> /// The current offset inside the window (relative to the window start). /// </summary> public int Offset { get { return _offset; } } /// <summary> /// The buffer backing the current window. /// </summary> public char[] CharacterWindow { get { return _characterWindow; } } /// <summary> /// Returns the start of the current lexeme relative to the window start. /// </summary> public int LexemeRelativeStart { get { return _lexemeStart; } } /// <summary> /// Number of characters in the character window. /// </summary> public int CharacterWindowCount { get { return _characterWindowCount; } } /// <summary> /// The absolute position of the start of the current lexeme in the given /// SourceText. /// </summary> public int LexemeStartPosition { get { return _basis + _lexemeStart; } } /// <summary> /// The number of characters in the current lexeme. /// </summary> public int Width { get { return _offset - _lexemeStart; } } /// <summary> /// Start parsing a new lexeme. /// </summary> public void Start() { _lexemeStart = _offset; } public void Reset(int position) { // if position is within already read character range then just use what we have int relative = position - _basis; if (relative >= 0 && relative <= _characterWindowCount) { _offset = relative; } else { // we need to reread text buffer int amountToRead = Math.Min(_text.Length, position + _characterWindow.Length) - position; amountToRead = Math.Max(amountToRead, 0); if (amountToRead > 0) { _text.CopyTo(position, _characterWindow, 0, amountToRead); } _lexemeStart = 0; _offset = 0; _basis = position; _characterWindowCount = amountToRead; } } private bool MoreChars() { if (_offset >= _characterWindowCount) { if (this.Position >= _textEnd) { return false; } // if lexeme scanning is sufficiently into the char buffer, // then refocus the window onto the lexeme if (_lexemeStart > (_characterWindowCount / 4)) { Array.Copy(_characterWindow, _lexemeStart, _characterWindow, 0, _characterWindowCount - _lexemeStart); _characterWindowCount -= _lexemeStart; _offset -= _lexemeStart; _basis += _lexemeStart; _lexemeStart = 0; } if (_characterWindowCount >= _characterWindow.Length) { // grow char array, since we need more contiguous space char[] oldWindow = _characterWindow; char[] newWindow = new char[_characterWindow.Length * 2]; Array.Copy(oldWindow, 0, newWindow, 0, _characterWindowCount); s_windowPool.ForgetTrackedObject(oldWindow, newWindow); _characterWindow = newWindow; } int amountToRead = Math.Min(_textEnd - (_basis + _characterWindowCount), _characterWindow.Length - _characterWindowCount); _text.CopyTo(_basis + _characterWindowCount, _characterWindow, _characterWindowCount, amountToRead); _characterWindowCount += amountToRead; return amountToRead > 0; } return true; } /// <summary> /// After reading <see cref=" InvalidCharacter"/>, a consumer can determine /// if the InvalidCharacter was in the user's source or a sentinel. /// /// Comments and string literals are allowed to contain any Unicode character. /// </summary> /// <returns></returns> internal bool IsReallyAtEnd() { return _offset >= _characterWindowCount && Position >= _textEnd; } /// <summary> /// Advance the current position by one. No guarantee that this /// position is valid. /// </summary> public void AdvanceChar() { _offset++; } /// <summary> /// Advance the current position by n. No guarantee that this position /// is valid. /// </summary> public void AdvanceChar(int n) { _offset += n; } /// <summary> /// Grab the next character and advance the position. /// </summary> /// <returns> /// The next character, <see cref="InvalidCharacter" /> if there were no characters /// remaining. /// </returns> public char NextChar() { char c = PeekChar(); if (c != InvalidCharacter) { this.AdvanceChar(); } return c; } /// <summary> /// Gets the next character if there are any characters in the /// SourceText. May advance the window if we are at the end. /// </summary> /// <returns> /// The next character if any are available. InvalidCharacter otherwise. /// </returns> public char PeekChar() { if (_offset >= _characterWindowCount && !MoreChars()) { return InvalidCharacter; } // N.B. MoreChars may update the offset. return _characterWindow[_offset]; } /// <summary> /// Gets the character at the given offset to the current position if /// the position is valid within the SourceText. /// </summary> /// <returns> /// The next character if any are available. InvalidCharacter otherwise. /// </returns> public char PeekChar(int delta) { int position = this.Position; this.AdvanceChar(delta); char ch; if (_offset >= _characterWindowCount && !MoreChars()) { ch = InvalidCharacter; } else { // N.B. MoreChars may update the offset. ch = _characterWindow[_offset]; } this.Reset(position); return ch; } public bool IsUnicodeEscape() { if (this.PeekChar() == '\\') { var ch2 = this.PeekChar(1); if (ch2 == 'U' || ch2 == 'u') { return true; } } return false; } public char PeekCharOrUnicodeEscape(out char surrogateCharacter) { if (this.IsUnicodeEscape()) { return this.PeekUnicodeEscape(out surrogateCharacter); } else { surrogateCharacter = InvalidCharacter; return this.PeekChar(); } } public char PeekUnicodeEscape(out char surrogateCharacter) { int position = this.Position; // if we're peeking, then we don't want to change the position SyntaxDiagnosticInfo info; var ch = this.ScanUnicodeEscape(peek: true, surrogateCharacter: out surrogateCharacter, info: out info); Debug.Assert(info == null, "Never produce a diagnostic while peeking."); this.Reset(position); return ch; } public char NextCharOrUnicodeEscape(out char surrogateCharacter, out SyntaxDiagnosticInfo info) { var ch = this.PeekChar(); Debug.Assert(ch != InvalidCharacter, "Precondition established by all callers; required for correctness of AdvanceChar() call."); if (ch == '\\') { var ch2 = this.PeekChar(1); if (ch2 == 'U' || ch2 == 'u') { return this.ScanUnicodeEscape(peek: false, surrogateCharacter: out surrogateCharacter, info: out info); } } surrogateCharacter = InvalidCharacter; info = null; this.AdvanceChar(); return ch; } public char NextUnicodeEscape(out char surrogateCharacter, out SyntaxDiagnosticInfo info) { return ScanUnicodeEscape(peek: false, surrogateCharacter: out surrogateCharacter, info: out info); } private char ScanUnicodeEscape(bool peek, out char surrogateCharacter, out SyntaxDiagnosticInfo info) { surrogateCharacter = InvalidCharacter; info = null; int start = this.Position; char character = this.PeekChar(); Debug.Assert(character == '\\'); this.AdvanceChar(); character = this.PeekChar(); if (character == 'U') { uint uintChar = 0; this.AdvanceChar(); if (!SyntaxFacts.IsHexDigit(this.PeekChar())) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { for (int i = 0; i < 8; i++) { character = this.PeekChar(); if (!SyntaxFacts.IsHexDigit(character)) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } break; } uintChar = (uint)((uintChar << 4) + SyntaxFacts.HexValue(character)); this.AdvanceChar(); } if (uintChar > 0x0010FFFF) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { character = GetCharsFromUtf32(uintChar, out surrogateCharacter); } } } else { Debug.Assert(character == 'u' || character == 'x'); int intChar = 0; this.AdvanceChar(); if (!SyntaxFacts.IsHexDigit(this.PeekChar())) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { for (int i = 0; i < 4; i++) { char ch2 = this.PeekChar(); if (!SyntaxFacts.IsHexDigit(ch2)) { if (character == 'u') { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } break; } intChar = (intChar << 4) + SyntaxFacts.HexValue(ch2); this.AdvanceChar(); } character = (char)intChar; } } return character; } /// <summary> /// Given that the next character is an ampersand ('&amp;'), attempt to interpret the /// following characters as an XML entity. On success, populate the out parameters /// with the low and high UTF-16 surrogates for the character represented by the /// entity. /// </summary> /// <param name="ch">e.g. '&lt;' for &amp;lt;.</param> /// <param name="surrogate">e.g. '\uDC00' for &amp;#x10000; (ch == '\uD800').</param> /// <returns>True if a valid XML entity was consumed.</returns> /// <remarks> /// NOTE: Always advances, even on failure. /// </remarks> public bool TryScanXmlEntity(out char ch, out char surrogate) { Debug.Assert(this.PeekChar() == '&'); ch = '&'; this.AdvanceChar(); surrogate = InvalidCharacter; switch (this.PeekChar()) { case 'l': if (AdvanceIfMatches("lt;")) { ch = '<'; return true; } break; case 'g': if (AdvanceIfMatches("gt;")) { ch = '>'; return true; } break; case 'a': if (AdvanceIfMatches("amp;")) { ch = '&'; return true; } else if (AdvanceIfMatches("apos;")) { ch = '\''; return true; } break; case 'q': if (AdvanceIfMatches("quot;")) { ch = '"'; return true; } break; case '#': { this.AdvanceChar(); //# uint uintChar = 0; if (AdvanceIfMatches("x")) { char digit; while (SyntaxFacts.IsHexDigit(digit = this.PeekChar())) { this.AdvanceChar(); // disallow overflow if (uintChar <= 0x7FFFFFF) { uintChar = (uintChar << 4) + (uint)SyntaxFacts.HexValue(digit); } else { return false; } } } else { char digit; while (SyntaxFacts.IsDecDigit(digit = this.PeekChar())) { this.AdvanceChar(); // disallow overflow if (uintChar <= 0x7FFFFFF) { uintChar = (uintChar << 3) + (uintChar << 1) + (uint)SyntaxFacts.DecValue(digit); } else { return false; } } } if (AdvanceIfMatches(";")) { ch = GetCharsFromUtf32(uintChar, out surrogate); return true; } break; } } return false; } /// <summary> /// If the next characters in the window match the given string, /// then advance past those characters. Otherwise, do nothing. /// </summary> private bool AdvanceIfMatches(string desired) { int length = desired.Length; for (int i = 0; i < length; i++) { if (PeekChar(i) != desired[i]) { return false; } } AdvanceChar(length); return true; } private SyntaxDiagnosticInfo CreateIllegalEscapeDiagnostic(int start) { return new SyntaxDiagnosticInfo(start - this.LexemeStartPosition, this.Position - start, ErrorCode.ERR_IllegalEscape); } public string Intern(StringBuilder text) { return _strings.Add(text); } public string Intern(char[] array, int start, int length) { return _strings.Add(array, start, length); } public string GetInternedText() { return this.Intern(_characterWindow, _lexemeStart, this.Width); } public string GetText(bool intern) { return this.GetText(this.LexemeStartPosition, this.Width, intern); } public string GetText(int position, int length, bool intern) { int offset = position - _basis; // PERF: Whether interning or not, there are some frequently occurring // easy cases we can pick off easily. switch (length) { case 0: return string.Empty; case 1: if (_characterWindow[offset] == ' ') { return " "; } if (_characterWindow[offset] == '\n') { return "\n"; } break; case 2: char firstChar = _characterWindow[offset]; if (firstChar == '\r' && _characterWindow[offset + 1] == '\n') { return "\r\n"; } if (firstChar == '/' && _characterWindow[offset + 1] == '/') { return "//"; } break; case 3: if (_characterWindow[offset] == '/' && _characterWindow[offset + 1] == '/' && _characterWindow[offset + 2] == ' ') { return "// "; } break; } if (intern) { return this.Intern(_characterWindow, offset, length); } else { return new string(_characterWindow, offset, length); } } internal static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate) { if (codepoint < (uint)0x00010000) { lowSurrogate = InvalidCharacter; return (char)codepoint; } else { Debug.Assert(codepoint > 0x0000FFFF && codepoint <= 0x0010FFFF); lowSurrogate = (char)((codepoint - 0x00010000) % 0x0400 + 0xDC00); return (char)((codepoint - 0x00010000) / 0x0400 + 0xD800); } } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/EditorFeatures/Core.Wpf/InlineRename/Dashboard/DashboardViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Windows; using Microsoft.CodeAnalysis.Rename; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal class DashboardViewModel : INotifyPropertyChanged, IDisposable { private readonly Visibility _renameOverloadsVisibility; private DashboardSeverity _severity = DashboardSeverity.None; private readonly InlineRenameSession _session; private string _searchText; private int _resolvableConflictCount; private int _unresolvableConflictCount; private string _errorText; private bool _defaultRenameOverloadFlag; private readonly bool _isRenameOverloadsEditable; private bool _defaultRenameInStringsFlag; private bool _defaultRenameInCommentsFlag; private bool _defaultRenameFileFlag; private bool _defaultPreviewChangesFlag; private bool _isReplacementTextValid; public DashboardViewModel(InlineRenameSession session) { Contract.ThrowIfNull(session); _session = session; _searchText = EditorFeaturesResources.Searching; _renameOverloadsVisibility = session.HasRenameOverloads ? Visibility.Visible : Visibility.Collapsed; _isRenameOverloadsEditable = !session.ForceRenameOverloads; _defaultRenameOverloadFlag = session.OptionSet.GetOption(RenameOptions.RenameOverloads) || session.ForceRenameOverloads; _defaultRenameInStringsFlag = session.OptionSet.GetOption(RenameOptions.RenameInStrings); _defaultRenameInCommentsFlag = session.OptionSet.GetOption(RenameOptions.RenameInComments); _defaultPreviewChangesFlag = session.OptionSet.GetOption(RenameOptions.PreviewChanges); _session.ReferenceLocationsChanged += OnReferenceLocationsChanged; _session.ReplacementsComputed += OnReplacementsComputed; _session.ReplacementTextChanged += OnReplacementTextChanged; // Set the flag to true by default if we're showing the option. _isReplacementTextValid = true; ComputeDefaultRenameFileFlag(); } public event PropertyChangedEventHandler PropertyChanged; private void OnReferenceLocationsChanged(object sender, ImmutableArray<InlineRenameLocation> renameLocations) { var totalFilesCount = renameLocations.GroupBy(s => s.Document).Count(); var totalSpansCount = renameLocations.Length; UpdateSearchText(totalSpansCount, totalFilesCount); } private void OnIsReplacementTextValidChanged(bool isReplacementTextValid) { if (isReplacementTextValid == _isReplacementTextValid) { return; } _isReplacementTextValid = isReplacementTextValid; ComputeDefaultRenameFileFlag(); NotifyPropertyChanged(nameof(AllowFileRename)); } private void ComputeDefaultRenameFileFlag() { // If replacementText is invalid, we won't rename the file. DefaultRenameFileFlag = _isReplacementTextValid && (_session.OptionSet.GetOption(RenameOptions.RenameFile) || AllowFileRename); } private void OnReplacementsComputed(object sender, IInlineRenameReplacementInfo result) { var session = (InlineRenameSession)sender; _resolvableConflictCount = 0; _unresolvableConflictCount = 0; OnIsReplacementTextValidChanged(result.ReplacementTextValid); if (result.ReplacementTextValid) { _errorText = null; foreach (var resolution in result.GetAllReplacementKinds()) { switch (resolution) { case InlineRenameReplacementKind.ResolvedReferenceConflict: case InlineRenameReplacementKind.ResolvedNonReferenceConflict: _resolvableConflictCount++; break; case InlineRenameReplacementKind.UnresolvedConflict: _unresolvableConflictCount++; break; } } } else { _errorText = string.IsNullOrEmpty(session.ReplacementText) ? null : EditorFeaturesResources.The_new_name_is_not_a_valid_identifier; } UpdateSeverity(); AllPropertiesChanged(); } private void OnReplacementTextChanged(object sender, EventArgs args) { // When the new name changes, we need to update the display of the new name or the // instructional text, depending on whether the new name and the original name are // distinct. NotifyPropertyChanged(nameof(ShouldShowInstructions)); NotifyPropertyChanged(nameof(ShouldShowNewName)); NotifyPropertyChanged(nameof(NewNameDescription)); } private void NotifyPropertyChanged([CallerMemberName] string name = null) => this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); private void AllPropertiesChanged() => NotifyPropertyChanged(string.Empty); private void UpdateSearchText(int referenceCount, int fileCount) { if (referenceCount == 1 && fileCount == 1) { _searchText = EditorFeaturesResources.Rename_will_update_1_reference_in_1_file; } else if (fileCount == 1) { _searchText = string.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, referenceCount); } else { _searchText = string.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_files, referenceCount, fileCount); } NotifyPropertyChanged("SearchText"); } private void UpdateSeverity() { if (_errorText != null || _unresolvableConflictCount > 0) { _severity = DashboardSeverity.Error; } else if (_resolvableConflictCount > 0) { _severity = DashboardSeverity.Info; } else { _severity = DashboardSeverity.None; } } public InlineRenameSession Session => _session; public DashboardSeverity Severity => _severity; public bool AllowFileRename => _session.FileRenameInfo == InlineRenameFileRenameInfo.Allowed && _isReplacementTextValid; public bool ShowFileRename => _session.FileRenameInfo != InlineRenameFileRenameInfo.NotAllowed; public string FileRenameString => _session.FileRenameInfo switch { InlineRenameFileRenameInfo.TypeDoesNotMatchFileName => EditorFeaturesResources.Rename_file_name_doesnt_match, InlineRenameFileRenameInfo.TypeWithMultipleLocations => EditorFeaturesResources.Rename_file_partial_type, _ => EditorFeaturesResources.Rename_symbols_file }; public string HeaderText { get { return string.Format(EditorFeaturesResources.Rename_colon_0, Session.OriginalSymbolName); } } public string NewNameDescription { get { return string.Format(EditorFeaturesResources.New_name_colon_0, Session.ReplacementText); } } public bool ShouldShowInstructions { get { return Session.OriginalSymbolName == Session.ReplacementText; } } public bool ShouldShowNewName { get { return !ShouldShowInstructions; } } public string SearchText => _searchText; public bool HasResolvableConflicts { get { return _resolvableConflictCount > 0; } } public string ResolvableConflictText { get { return _resolvableConflictCount >= 1 ? string.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, _resolvableConflictCount) : null; } } public bool HasUnresolvableConflicts { get { return _unresolvableConflictCount > 0; } } public string UnresolvableConflictText { get { return _unresolvableConflictCount >= 1 ? string.Format(EditorFeaturesResources._0_unresolvable_conflict_s, _unresolvableConflictCount) : null; } } public bool HasError { get { return _errorText != null; } } public string ErrorText => _errorText; public Visibility RenameOverloadsVisibility => _renameOverloadsVisibility; public bool IsRenameOverloadsEditable => _isRenameOverloadsEditable; public bool DefaultRenameOverloadFlag { get { return _defaultRenameOverloadFlag; } set { if (IsRenameOverloadsEditable) { _defaultRenameOverloadFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameOverloads, value); } } } public bool DefaultRenameInStringsFlag { get { return _defaultRenameInStringsFlag; } set { _defaultRenameInStringsFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInStrings, value); } } public bool DefaultRenameInCommentsFlag { get { return _defaultRenameInCommentsFlag; } set { _defaultRenameInCommentsFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, value); } } public bool DefaultRenameFileFlag { get => _defaultRenameFileFlag; set { _defaultRenameFileFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameFile, value); } } public bool DefaultPreviewChangesFlag { get { return _defaultPreviewChangesFlag; } set { _defaultPreviewChangesFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.PreviewChanges, value); } } public string OriginalName => _session.OriginalSymbolName; public void Dispose() { _session.ReplacementTextChanged -= OnReplacementTextChanged; _session.ReferenceLocationsChanged -= OnReferenceLocationsChanged; _session.ReplacementsComputed -= OnReplacementsComputed; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Windows; using Microsoft.CodeAnalysis.Rename; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal class DashboardViewModel : INotifyPropertyChanged, IDisposable { private readonly Visibility _renameOverloadsVisibility; private DashboardSeverity _severity = DashboardSeverity.None; private readonly InlineRenameSession _session; private string _searchText; private int _resolvableConflictCount; private int _unresolvableConflictCount; private string _errorText; private bool _defaultRenameOverloadFlag; private readonly bool _isRenameOverloadsEditable; private bool _defaultRenameInStringsFlag; private bool _defaultRenameInCommentsFlag; private bool _defaultRenameFileFlag; private bool _defaultPreviewChangesFlag; private bool _isReplacementTextValid; public DashboardViewModel(InlineRenameSession session) { Contract.ThrowIfNull(session); _session = session; _searchText = EditorFeaturesResources.Searching; _renameOverloadsVisibility = session.HasRenameOverloads ? Visibility.Visible : Visibility.Collapsed; _isRenameOverloadsEditable = !session.ForceRenameOverloads; _defaultRenameOverloadFlag = session.OptionSet.GetOption(RenameOptions.RenameOverloads) || session.ForceRenameOverloads; _defaultRenameInStringsFlag = session.OptionSet.GetOption(RenameOptions.RenameInStrings); _defaultRenameInCommentsFlag = session.OptionSet.GetOption(RenameOptions.RenameInComments); _defaultPreviewChangesFlag = session.OptionSet.GetOption(RenameOptions.PreviewChanges); _session.ReferenceLocationsChanged += OnReferenceLocationsChanged; _session.ReplacementsComputed += OnReplacementsComputed; _session.ReplacementTextChanged += OnReplacementTextChanged; // Set the flag to true by default if we're showing the option. _isReplacementTextValid = true; ComputeDefaultRenameFileFlag(); } public event PropertyChangedEventHandler PropertyChanged; private void OnReferenceLocationsChanged(object sender, ImmutableArray<InlineRenameLocation> renameLocations) { var totalFilesCount = renameLocations.GroupBy(s => s.Document).Count(); var totalSpansCount = renameLocations.Length; UpdateSearchText(totalSpansCount, totalFilesCount); } private void OnIsReplacementTextValidChanged(bool isReplacementTextValid) { if (isReplacementTextValid == _isReplacementTextValid) { return; } _isReplacementTextValid = isReplacementTextValid; ComputeDefaultRenameFileFlag(); NotifyPropertyChanged(nameof(AllowFileRename)); } private void ComputeDefaultRenameFileFlag() { // If replacementText is invalid, we won't rename the file. DefaultRenameFileFlag = _isReplacementTextValid && (_session.OptionSet.GetOption(RenameOptions.RenameFile) || AllowFileRename); } private void OnReplacementsComputed(object sender, IInlineRenameReplacementInfo result) { var session = (InlineRenameSession)sender; _resolvableConflictCount = 0; _unresolvableConflictCount = 0; OnIsReplacementTextValidChanged(result.ReplacementTextValid); if (result.ReplacementTextValid) { _errorText = null; foreach (var resolution in result.GetAllReplacementKinds()) { switch (resolution) { case InlineRenameReplacementKind.ResolvedReferenceConflict: case InlineRenameReplacementKind.ResolvedNonReferenceConflict: _resolvableConflictCount++; break; case InlineRenameReplacementKind.UnresolvedConflict: _unresolvableConflictCount++; break; } } } else { _errorText = string.IsNullOrEmpty(session.ReplacementText) ? null : EditorFeaturesResources.The_new_name_is_not_a_valid_identifier; } UpdateSeverity(); AllPropertiesChanged(); } private void OnReplacementTextChanged(object sender, EventArgs args) { // When the new name changes, we need to update the display of the new name or the // instructional text, depending on whether the new name and the original name are // distinct. NotifyPropertyChanged(nameof(ShouldShowInstructions)); NotifyPropertyChanged(nameof(ShouldShowNewName)); NotifyPropertyChanged(nameof(NewNameDescription)); } private void NotifyPropertyChanged([CallerMemberName] string name = null) => this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); private void AllPropertiesChanged() => NotifyPropertyChanged(string.Empty); private void UpdateSearchText(int referenceCount, int fileCount) { if (referenceCount == 1 && fileCount == 1) { _searchText = EditorFeaturesResources.Rename_will_update_1_reference_in_1_file; } else if (fileCount == 1) { _searchText = string.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, referenceCount); } else { _searchText = string.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_files, referenceCount, fileCount); } NotifyPropertyChanged("SearchText"); } private void UpdateSeverity() { if (_errorText != null || _unresolvableConflictCount > 0) { _severity = DashboardSeverity.Error; } else if (_resolvableConflictCount > 0) { _severity = DashboardSeverity.Info; } else { _severity = DashboardSeverity.None; } } public InlineRenameSession Session => _session; public DashboardSeverity Severity => _severity; public bool AllowFileRename => _session.FileRenameInfo == InlineRenameFileRenameInfo.Allowed && _isReplacementTextValid; public bool ShowFileRename => _session.FileRenameInfo != InlineRenameFileRenameInfo.NotAllowed; public string FileRenameString => _session.FileRenameInfo switch { InlineRenameFileRenameInfo.TypeDoesNotMatchFileName => EditorFeaturesResources.Rename_file_name_doesnt_match, InlineRenameFileRenameInfo.TypeWithMultipleLocations => EditorFeaturesResources.Rename_file_partial_type, _ => EditorFeaturesResources.Rename_symbols_file }; public string HeaderText { get { return string.Format(EditorFeaturesResources.Rename_colon_0, Session.OriginalSymbolName); } } public string NewNameDescription { get { return string.Format(EditorFeaturesResources.New_name_colon_0, Session.ReplacementText); } } public bool ShouldShowInstructions { get { return Session.OriginalSymbolName == Session.ReplacementText; } } public bool ShouldShowNewName { get { return !ShouldShowInstructions; } } public string SearchText => _searchText; public bool HasResolvableConflicts { get { return _resolvableConflictCount > 0; } } public string ResolvableConflictText { get { return _resolvableConflictCount >= 1 ? string.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, _resolvableConflictCount) : null; } } public bool HasUnresolvableConflicts { get { return _unresolvableConflictCount > 0; } } public string UnresolvableConflictText { get { return _unresolvableConflictCount >= 1 ? string.Format(EditorFeaturesResources._0_unresolvable_conflict_s, _unresolvableConflictCount) : null; } } public bool HasError { get { return _errorText != null; } } public string ErrorText => _errorText; public Visibility RenameOverloadsVisibility => _renameOverloadsVisibility; public bool IsRenameOverloadsEditable => _isRenameOverloadsEditable; public bool DefaultRenameOverloadFlag { get { return _defaultRenameOverloadFlag; } set { if (IsRenameOverloadsEditable) { _defaultRenameOverloadFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameOverloads, value); } } } public bool DefaultRenameInStringsFlag { get { return _defaultRenameInStringsFlag; } set { _defaultRenameInStringsFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInStrings, value); } } public bool DefaultRenameInCommentsFlag { get { return _defaultRenameInCommentsFlag; } set { _defaultRenameInCommentsFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, value); } } public bool DefaultRenameFileFlag { get => _defaultRenameFileFlag; set { _defaultRenameFileFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameFile, value); } } public bool DefaultPreviewChangesFlag { get { return _defaultPreviewChangesFlag; } set { _defaultPreviewChangesFlag = value; _session.RefreshRenameSessionWithOptionsChanged(RenameOptions.PreviewChanges, value); } } public string OriginalName => _session.OriginalSymbolName; public void Dispose() { _session.ReplacementTextChanged -= OnReplacementTextChanged; _session.ReferenceLocationsChanged -= OnReferenceLocationsChanged; _session.ReplacementsComputed -= OnReplacementsComputed; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Features/CSharp/Portable/GenerateDefaultConstructors/CSharpGenerateDefaultConstructorsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.GenerateDefaultConstructors { [ExportLanguageService(typeof(IGenerateDefaultConstructorsService), LanguageNames.CSharp), Shared] internal class CSharpGenerateDefaultConstructorsService : AbstractGenerateDefaultConstructorsService<CSharpGenerateDefaultConstructorsService> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateDefaultConstructorsService() { } protected override bool TryInitializeState( SemanticDocument semanticDocument, TextSpan textSpan, CancellationToken cancellationToken, [NotNullWhen(true)] out INamedTypeSymbol? classType) { cancellationToken.ThrowIfCancellationRequested(); // Offer the feature if we're on the header / between members of the class/struct, // or if we're on the first base-type of a class var helpers = semanticDocument.Document.GetRequiredLanguageService<IRefactoringHelpersService>(); if (helpers.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, out var typeDeclaration) || helpers.IsBetweenTypeMembers(semanticDocument.Text, semanticDocument.Root, textSpan.Start, out typeDeclaration)) { classType = semanticDocument.SemanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken) as INamedTypeSymbol; return classType?.TypeKind == TypeKind.Class; } var syntaxTree = semanticDocument.SyntaxTree; var node = semanticDocument.Root.FindToken(textSpan.Start).GetAncestor<TypeSyntax>(); if (node != null) { if (node.Parent is BaseTypeSyntax && node.Parent.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax? baseList)) { if (baseList.Parent != null && baseList.Types.Count > 0 && baseList.Types[0].Type == node && baseList.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration)) { var semanticModel = semanticDocument.SemanticModel; classType = semanticModel.GetDeclaredSymbol(baseList.Parent, cancellationToken) as INamedTypeSymbol; return classType != null; } } } classType = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.GenerateDefaultConstructors { [ExportLanguageService(typeof(IGenerateDefaultConstructorsService), LanguageNames.CSharp), Shared] internal class CSharpGenerateDefaultConstructorsService : AbstractGenerateDefaultConstructorsService<CSharpGenerateDefaultConstructorsService> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateDefaultConstructorsService() { } protected override bool TryInitializeState( SemanticDocument semanticDocument, TextSpan textSpan, CancellationToken cancellationToken, [NotNullWhen(true)] out INamedTypeSymbol? classType) { cancellationToken.ThrowIfCancellationRequested(); // Offer the feature if we're on the header / between members of the class/struct, // or if we're on the first base-type of a class var helpers = semanticDocument.Document.GetRequiredLanguageService<IRefactoringHelpersService>(); if (helpers.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, out var typeDeclaration) || helpers.IsBetweenTypeMembers(semanticDocument.Text, semanticDocument.Root, textSpan.Start, out typeDeclaration)) { classType = semanticDocument.SemanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken) as INamedTypeSymbol; return classType?.TypeKind == TypeKind.Class; } var syntaxTree = semanticDocument.SyntaxTree; var node = semanticDocument.Root.FindToken(textSpan.Start).GetAncestor<TypeSyntax>(); if (node != null) { if (node.Parent is BaseTypeSyntax && node.Parent.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax? baseList)) { if (baseList.Parent != null && baseList.Types.Count > 0 && baseList.Types[0].Type == node && baseList.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration)) { var semanticModel = semanticDocument.SemanticModel; classType = semanticModel.GetDeclaredSymbol(baseList.Parent, cancellationToken) as INamedTypeSymbol; return classType != null; } } } classType = null; return false; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Emitter/NoPia/EmbeddedEvent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Collections.Generic; #if !DEBUG using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol; #endif namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia { internal sealed class EmbeddedEvent : EmbeddedTypesManager.CommonEmbeddedEvent { public EmbeddedEvent(EventSymbolAdapter underlyingEvent, EmbeddedMethod adder, EmbeddedMethod remover) : base(underlyingEvent, adder, remover, null) { } protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return UnderlyingEvent.AdaptedEventSymbol.GetCustomAttributesToEmit(moduleBuilder); } protected override bool IsRuntimeSpecial { get { return UnderlyingEvent.AdaptedEventSymbol.HasRuntimeSpecialName; } } protected override bool IsSpecialName { get { return UnderlyingEvent.AdaptedEventSymbol.HasSpecialName; } } protected override Cci.ITypeReference GetType(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return moduleBuilder.Translate(UnderlyingEvent.AdaptedEventSymbol.Type, syntaxNodeOpt, diagnostics); } protected override EmbeddedType ContainingType { get { return AnAccessor.ContainingType; } } protected override Cci.TypeMemberVisibility Visibility { get { return PEModuleBuilder.MemberVisibility(UnderlyingEvent.AdaptedEventSymbol); } } protected override string Name { get { return UnderlyingEvent.AdaptedEventSymbol.MetadataName; } } protected override void EmbedCorrespondingComEventInterfaceMethodInternal(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) { // If the event happens to belong to a class with a ComEventInterfaceAttribute, there will also be // a paired method living on its source interface. The ComAwareEventInfo class expects to find this // method through reflection. If we embed an event, therefore, we must ensure that the associated source // interface method is also included, even if it is not otherwise referenced in the embedding project. NamedTypeSymbol underlyingContainingType = ContainingType.UnderlyingNamedType.AdaptedNamedTypeSymbol; foreach (var attrData in underlyingContainingType.GetAttributes()) { if (attrData.IsTargetAttribute(underlyingContainingType, AttributeDescription.ComEventInterfaceAttribute)) { bool foundMatch = false; NamedTypeSymbol sourceInterface = null; if (attrData.CommonConstructorArguments.Length == 2) { sourceInterface = attrData.CommonConstructorArguments[0].ValueInternal as NamedTypeSymbol; if ((object)sourceInterface != null) { foundMatch = EmbedMatchingInterfaceMethods(sourceInterface, syntaxNodeOpt, diagnostics); foreach (NamedTypeSymbol source in sourceInterface.AllInterfacesNoUseSiteDiagnostics) { if (EmbedMatchingInterfaceMethods(source, syntaxNodeOpt, diagnostics)) { foundMatch = true; } } } } if (!foundMatch && isUsedForComAwareEventBinding) { if ((object)sourceInterface == null) { // ERRID_SourceInterfaceMustBeInterface/ERR_MissingSourceInterface EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingSourceInterface, syntaxNodeOpt, underlyingContainingType, UnderlyingEvent.AdaptedEventSymbol); } else { var useSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; sourceInterface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); diagnostics.Add(syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location, useSiteInfo.Diagnostics); // ERRID_EventNoPIANoBackingMember/ERR_MissingMethodOnSourceInterface EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingMethodOnSourceInterface, syntaxNodeOpt, sourceInterface, UnderlyingEvent.AdaptedEventSymbol.MetadataName, UnderlyingEvent.AdaptedEventSymbol); } } break; } } } private bool EmbedMatchingInterfaceMethods(NamedTypeSymbol sourceInterface, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { bool foundMatch = false; foreach (Symbol m in sourceInterface.GetMembers(UnderlyingEvent.AdaptedEventSymbol.MetadataName)) { if (m.Kind == SymbolKind.Method) { TypeManager.EmbedMethodIfNeedTo(((MethodSymbol)m).GetCciAdapter(), syntaxNodeOpt, diagnostics); foundMatch = true; } } return foundMatch; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Collections.Generic; #if !DEBUG using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol; #endif namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia { internal sealed class EmbeddedEvent : EmbeddedTypesManager.CommonEmbeddedEvent { public EmbeddedEvent(EventSymbolAdapter underlyingEvent, EmbeddedMethod adder, EmbeddedMethod remover) : base(underlyingEvent, adder, remover, null) { } protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return UnderlyingEvent.AdaptedEventSymbol.GetCustomAttributesToEmit(moduleBuilder); } protected override bool IsRuntimeSpecial { get { return UnderlyingEvent.AdaptedEventSymbol.HasRuntimeSpecialName; } } protected override bool IsSpecialName { get { return UnderlyingEvent.AdaptedEventSymbol.HasSpecialName; } } protected override Cci.ITypeReference GetType(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return moduleBuilder.Translate(UnderlyingEvent.AdaptedEventSymbol.Type, syntaxNodeOpt, diagnostics); } protected override EmbeddedType ContainingType { get { return AnAccessor.ContainingType; } } protected override Cci.TypeMemberVisibility Visibility { get { return PEModuleBuilder.MemberVisibility(UnderlyingEvent.AdaptedEventSymbol); } } protected override string Name { get { return UnderlyingEvent.AdaptedEventSymbol.MetadataName; } } protected override void EmbedCorrespondingComEventInterfaceMethodInternal(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) { // If the event happens to belong to a class with a ComEventInterfaceAttribute, there will also be // a paired method living on its source interface. The ComAwareEventInfo class expects to find this // method through reflection. If we embed an event, therefore, we must ensure that the associated source // interface method is also included, even if it is not otherwise referenced in the embedding project. NamedTypeSymbol underlyingContainingType = ContainingType.UnderlyingNamedType.AdaptedNamedTypeSymbol; foreach (var attrData in underlyingContainingType.GetAttributes()) { if (attrData.IsTargetAttribute(underlyingContainingType, AttributeDescription.ComEventInterfaceAttribute)) { bool foundMatch = false; NamedTypeSymbol sourceInterface = null; if (attrData.CommonConstructorArguments.Length == 2) { sourceInterface = attrData.CommonConstructorArguments[0].ValueInternal as NamedTypeSymbol; if ((object)sourceInterface != null) { foundMatch = EmbedMatchingInterfaceMethods(sourceInterface, syntaxNodeOpt, diagnostics); foreach (NamedTypeSymbol source in sourceInterface.AllInterfacesNoUseSiteDiagnostics) { if (EmbedMatchingInterfaceMethods(source, syntaxNodeOpt, diagnostics)) { foundMatch = true; } } } } if (!foundMatch && isUsedForComAwareEventBinding) { if ((object)sourceInterface == null) { // ERRID_SourceInterfaceMustBeInterface/ERR_MissingSourceInterface EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingSourceInterface, syntaxNodeOpt, underlyingContainingType, UnderlyingEvent.AdaptedEventSymbol); } else { var useSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; sourceInterface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); diagnostics.Add(syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location, useSiteInfo.Diagnostics); // ERRID_EventNoPIANoBackingMember/ERR_MissingMethodOnSourceInterface EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingMethodOnSourceInterface, syntaxNodeOpt, sourceInterface, UnderlyingEvent.AdaptedEventSymbol.MetadataName, UnderlyingEvent.AdaptedEventSymbol); } } break; } } } private bool EmbedMatchingInterfaceMethods(NamedTypeSymbol sourceInterface, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { bool foundMatch = false; foreach (Symbol m in sourceInterface.GetMembers(UnderlyingEvent.AdaptedEventSymbol.MetadataName)) { if (m.Kind == SymbolKind.Method) { TypeManager.EmbedMethodIfNeedTo(((MethodSymbol)m).GetCciAdapter(), syntaxNodeOpt, diagnostics); foundMatch = true; } } return foundMatch; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpAccessibilityFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using System.Diagnostics.CodeAnalysis; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpAccessibilityFacts : IAccessibilityFacts { public static readonly IAccessibilityFacts Instance = new CSharpAccessibilityFacts(); private CSharpAccessibilityFacts() { } public bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = GetDeclarationKind(declaration); return declarationKind is DeclarationKind.Field or DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) return Accessibility.NotApplicable; var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public static void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public static DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (declaration.Parent is not AttributeListSyntax parentList || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } public static SyntaxTokenList GetModifierTokens(SyntaxNode declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.GetRequiredParent()), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.GetRequiredParent()), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; public static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; public static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using System.Diagnostics.CodeAnalysis; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpAccessibilityFacts : IAccessibilityFacts { public static readonly IAccessibilityFacts Instance = new CSharpAccessibilityFacts(); private CSharpAccessibilityFacts() { } public bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = GetDeclarationKind(declaration); return declarationKind is DeclarationKind.Field or DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) return Accessibility.NotApplicable; var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public static void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public static DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (declaration.Parent is not AttributeListSyntax parentList || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } public static SyntaxTokenList GetModifierTokens(SyntaxNode declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.GetRequiredParent()), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.GetRequiredParent()), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; public static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; public static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/Core/Portable/LanguageServices/SemanticsFactsService/SemanticFacts/AbstractSemanticFactsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract partial class AbstractSemanticFactsService : ISemanticFacts { public string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize, CancellationToken cancellationToken) => SemanticFacts.GenerateNameForExpression(semanticModel, expression, capitalize, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract partial class AbstractSemanticFactsService : ISemanticFacts { public string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize, CancellationToken cancellationToken) => SemanticFacts.GenerateNameForExpression(semanticModel, expression, capitalize, cancellationToken); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceParameterService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal abstract partial class AbstractIntroduceParameterService< TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> : CodeRefactoringProvider where TExpressionSyntax : SyntaxNode where TInvocationExpressionSyntax : TExpressionSyntax where TObjectCreationExpressionSyntax : TExpressionSyntax where TIdentifierNameSyntax : TExpressionSyntax { protected abstract SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol); protected abstract SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments); protected abstract SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl); protected abstract bool IsDestructor(IMethodSymbol methodSymbol); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var expression = await document.TryGetRelevantNodeAsync<TExpressionSyntax>(textSpan, cancellationToken).ConfigureAwait(false); if (expression == null || CodeRefactoringHelpers.IsNodeUnderselected(expression, textSpan)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType is null or IErrorTypeSymbol) { return; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Need to special case for expressions that are contained within a parameter // because it is technically "contained" within a method, but an expression in a parameter does not make // sense to introduce. var parameterNode = expression.FirstAncestorOrSelf<SyntaxNode>(node => syntaxFacts.IsParameter(node)); if (parameterNode is not null) { return; } // Need to special case for highlighting of method types because they are also "contained" within a method, // but it does not make sense to introduce a parameter in that case. if (syntaxFacts.IsInNamespaceOrTypeContext(expression)) { return; } // Need to special case for expressions whose direct parent is a MemberAccessExpression since they will // never introduce a parameter that makes sense in that case. if (syntaxFacts.IsNameOfAnyMemberAccessExpression(expression)) { return; } var generator = SyntaxGenerator.GetGenerator(document); var containingMethod = expression.FirstAncestorOrSelf<SyntaxNode>(node => generator.GetParameterListNode(node) is not null); if (containingMethod is null) { return; } var containingSymbol = semanticModel.GetDeclaredSymbol(containingMethod, cancellationToken); if (containingSymbol is not IMethodSymbol methodSymbol) { return; } // Code actions for trampoline and overloads will not be offered if the method is a constructor. // Code actions for overloads will not be offered if the method if the method is a local function. var methodKind = methodSymbol.MethodKind; if (methodKind is not (MethodKind.Ordinary or MethodKind.LocalFunction or MethodKind.Constructor)) { return; } if (IsDestructor(methodSymbol)) { return; } var actions = await GetActionsAsync(document, expression, methodSymbol, containingMethod, cancellationToken).ConfigureAwait(false); if (actions is null) { return; } var singleLineExpression = syntaxFacts.ConvertToSingleLine(expression); var nodeString = singleLineExpression.ToString(); if (actions.Value.actions.Length > 0) { context.RegisterRefactoring(new CodeActionWithNestedActions( string.Format(FeaturesResources.Introduce_parameter_for_0, nodeString), actions.Value.actions, isInlinable: false, priority: CodeActionPriority.Low), textSpan); } if (actions.Value.actionsAllOccurrences.Length > 0) { context.RegisterRefactoring(new CodeActionWithNestedActions( string.Format(FeaturesResources.Introduce_parameter_for_all_occurrences_of_0, nodeString), actions.Value.actionsAllOccurrences, isInlinable: false, priority: CodeActionPriority.Low), textSpan); } } /// <summary> /// Creates new code actions for each introduce parameter possibility. /// Does not create actions for overloads/trampoline if there are optional parameters or if the methodSymbol /// is a constructor. /// </summary> private async Task<(ImmutableArray<CodeAction> actions, ImmutableArray<CodeAction> actionsAllOccurrences)?> GetActionsAsync(Document document, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, CancellationToken cancellationToken) { var (shouldDisplay, containsClassExpression) = await ShouldExpressionDisplayCodeActionAsync( document, expression, cancellationToken).ConfigureAwait(false); if (!shouldDisplay) { return null; } using var actionsBuilder = TemporaryArray<CodeAction>.Empty; using var actionsBuilderAllOccurrences = TemporaryArray<CodeAction>.Empty; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (!containsClassExpression) { actionsBuilder.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: false, IntroduceParameterCodeActionKind.Refactor)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: true, IntroduceParameterCodeActionKind.Refactor)); } if (methodSymbol.MethodKind is not MethodKind.Constructor) { actionsBuilder.Add(CreateNewCodeAction( FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: false, IntroduceParameterCodeActionKind.Trampoline)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction( FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: true, IntroduceParameterCodeActionKind.Trampoline)); if (methodSymbol.MethodKind is not MethodKind.LocalFunction) { actionsBuilder.Add(CreateNewCodeAction( FeaturesResources.into_new_overload, allOccurrences: false, IntroduceParameterCodeActionKind.Overload)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction( FeaturesResources.into_new_overload, allOccurrences: true, IntroduceParameterCodeActionKind.Overload)); } } return (actionsBuilder.ToImmutableAndClear(), actionsBuilderAllOccurrences.ToImmutableAndClear()); // Local function to create a code action with more ease MyCodeAction CreateNewCodeAction(string actionName, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction) { return new MyCodeAction(actionName, c => IntroduceParameterAsync( document, expression, methodSymbol, containingMethod, allOccurrences, selectedCodeAction, c)); } } /// <summary> /// Determines if the expression is something that should have code actions displayed for it. /// Depends upon the identifiers in the expression mapping back to parameters. /// Does not handle params parameters. /// </summary> private static async Task<(bool shouldDisplay, bool containsClassExpression)> ShouldExpressionDisplayCodeActionAsync( Document document, TExpressionSyntax expression, CancellationToken cancellationToken) { var variablesInExpression = expression.DescendantNodes(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var variable in variablesInExpression) { var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol; // If the expression contains locals or range variables then we do not want to offer // code actions since there will be errors at call sites. if (symbol is IRangeVariableSymbol or ILocalSymbol) { return (false, false); } if (symbol is IParameterSymbol parameter) { // We do not want to offer code actions if the expressions contains references // to params parameters because it is difficult to know what is being referenced // at the callsites. if (parameter.IsParams) { return (false, false); } } } // If expression contains this or base keywords, implicitly or explicitly, // then we do not want to refactor call sites that are not overloads/trampolines // because we do not know if the class specific information is available in other documents. var operation = semanticModel.GetOperation(expression, cancellationToken); var containsClassSpecificStatement = false; if (operation is not null) { containsClassSpecificStatement = operation.Descendants().Any(op => op.Kind == OperationKind.InstanceReference); } return (true, containsClassSpecificStatement); } /// <summary> /// Introduces a new parameter and refactors all the call sites based on the selected code action. /// </summary> private async Task<Solution> IntroduceParameterAsync(Document originalDocument, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction, CancellationToken cancellationToken) { var methodCallSites = await FindCallSitesAsync(originalDocument, methodSymbol, cancellationToken).ConfigureAwait(false); var modifiedSolution = originalDocument.Project.Solution; var rewriter = new IntroduceParameterDocumentRewriter(this, originalDocument, expression, methodSymbol, containingMethod, selectedCodeAction, allOccurrences); foreach (var (project, projectCallSites) in methodCallSites.GroupBy(kvp => kvp.Key.Project)) { var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var (document, invocations) in projectCallSites) { var newRoot = await rewriter.RewriteDocumentAsync(compilation, document, invocations, cancellationToken).ConfigureAwait(false); modifiedSolution = modifiedSolution.WithDocumentSyntaxRoot(originalDocument.Id, newRoot); } } return modifiedSolution; } /// <summary> /// Locates all the call sites of the method that introduced the parameter /// </summary> protected static async Task<Dictionary<Document, List<SyntaxNode>>> FindCallSitesAsync( Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken) { var methodCallSites = new Dictionary<Document, List<SyntaxNode>>(); var progress = new StreamingProgressCollector(); await SymbolFinder.FindReferencesAsync( methodSymbol, document.Project.Solution, progress, documents: null, FindReferencesSearchOptions.Default, cancellationToken).ConfigureAwait(false); var referencedSymbols = progress.GetReferencedSymbols(); // Ordering by descending to sort invocations by starting span to account for nested invocations var referencedLocations = referencedSymbols.SelectMany(referencedSymbol => referencedSymbol.Locations) .Distinct().Where(reference => !reference.IsImplicit) .OrderByDescending(reference => reference.Location.SourceSpan.Start); // Adding the original document to ensure that it will be seen again when processing the call sites // in order to update the original expression and containing method. methodCallSites.Add(document, new List<SyntaxNode>()); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var refLocation in referencedLocations) { // Does not support cross-language references currently if (refLocation.Document.Project.Language == document.Project.Language) { var reference = refLocation.Location.FindNode(cancellationToken).GetRequiredParent(); if (reference is not (TObjectCreationExpressionSyntax or TInvocationExpressionSyntax)) { reference = reference.GetRequiredParent(); } // Only adding items that are of type InvocationExpressionSyntax or TObjectCreationExpressionSyntax var invocationOrCreation = reference as TObjectCreationExpressionSyntax ?? (SyntaxNode?)(reference as TInvocationExpressionSyntax); if (invocationOrCreation is null) { continue; } if (!methodCallSites.TryGetValue(refLocation.Document, out var list)) { list = new List<SyntaxNode>(); methodCallSites.Add(refLocation.Document, list); } list.Add(invocationOrCreation); } } return methodCallSites; } private class MyCodeAction : SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } private enum IntroduceParameterCodeActionKind { Refactor, Trampoline, Overload } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal abstract partial class AbstractIntroduceParameterService< TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> : CodeRefactoringProvider where TExpressionSyntax : SyntaxNode where TInvocationExpressionSyntax : TExpressionSyntax where TObjectCreationExpressionSyntax : TExpressionSyntax where TIdentifierNameSyntax : TExpressionSyntax { protected abstract SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol); protected abstract SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments); protected abstract SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl); protected abstract bool IsDestructor(IMethodSymbol methodSymbol); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var expression = await document.TryGetRelevantNodeAsync<TExpressionSyntax>(textSpan, cancellationToken).ConfigureAwait(false); if (expression == null || CodeRefactoringHelpers.IsNodeUnderselected(expression, textSpan)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType is null or IErrorTypeSymbol) { return; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Need to special case for expressions that are contained within a parameter // because it is technically "contained" within a method, but an expression in a parameter does not make // sense to introduce. var parameterNode = expression.FirstAncestorOrSelf<SyntaxNode>(node => syntaxFacts.IsParameter(node)); if (parameterNode is not null) { return; } // Need to special case for highlighting of method types because they are also "contained" within a method, // but it does not make sense to introduce a parameter in that case. if (syntaxFacts.IsInNamespaceOrTypeContext(expression)) { return; } // Need to special case for expressions whose direct parent is a MemberAccessExpression since they will // never introduce a parameter that makes sense in that case. if (syntaxFacts.IsNameOfAnyMemberAccessExpression(expression)) { return; } var generator = SyntaxGenerator.GetGenerator(document); var containingMethod = expression.FirstAncestorOrSelf<SyntaxNode>(node => generator.GetParameterListNode(node) is not null); if (containingMethod is null) { return; } var containingSymbol = semanticModel.GetDeclaredSymbol(containingMethod, cancellationToken); if (containingSymbol is not IMethodSymbol methodSymbol) { return; } // Code actions for trampoline and overloads will not be offered if the method is a constructor. // Code actions for overloads will not be offered if the method if the method is a local function. var methodKind = methodSymbol.MethodKind; if (methodKind is not (MethodKind.Ordinary or MethodKind.LocalFunction or MethodKind.Constructor)) { return; } if (IsDestructor(methodSymbol)) { return; } var actions = await GetActionsAsync(document, expression, methodSymbol, containingMethod, cancellationToken).ConfigureAwait(false); if (actions is null) { return; } var singleLineExpression = syntaxFacts.ConvertToSingleLine(expression); var nodeString = singleLineExpression.ToString(); if (actions.Value.actions.Length > 0) { context.RegisterRefactoring(new CodeActionWithNestedActions( string.Format(FeaturesResources.Introduce_parameter_for_0, nodeString), actions.Value.actions, isInlinable: false, priority: CodeActionPriority.Low), textSpan); } if (actions.Value.actionsAllOccurrences.Length > 0) { context.RegisterRefactoring(new CodeActionWithNestedActions( string.Format(FeaturesResources.Introduce_parameter_for_all_occurrences_of_0, nodeString), actions.Value.actionsAllOccurrences, isInlinable: false, priority: CodeActionPriority.Low), textSpan); } } /// <summary> /// Creates new code actions for each introduce parameter possibility. /// Does not create actions for overloads/trampoline if there are optional parameters or if the methodSymbol /// is a constructor. /// </summary> private async Task<(ImmutableArray<CodeAction> actions, ImmutableArray<CodeAction> actionsAllOccurrences)?> GetActionsAsync(Document document, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, CancellationToken cancellationToken) { var (shouldDisplay, containsClassExpression) = await ShouldExpressionDisplayCodeActionAsync( document, expression, cancellationToken).ConfigureAwait(false); if (!shouldDisplay) { return null; } using var actionsBuilder = TemporaryArray<CodeAction>.Empty; using var actionsBuilderAllOccurrences = TemporaryArray<CodeAction>.Empty; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (!containsClassExpression) { actionsBuilder.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: false, IntroduceParameterCodeActionKind.Refactor)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: true, IntroduceParameterCodeActionKind.Refactor)); } if (methodSymbol.MethodKind is not MethodKind.Constructor) { actionsBuilder.Add(CreateNewCodeAction( FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: false, IntroduceParameterCodeActionKind.Trampoline)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction( FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: true, IntroduceParameterCodeActionKind.Trampoline)); if (methodSymbol.MethodKind is not MethodKind.LocalFunction) { actionsBuilder.Add(CreateNewCodeAction( FeaturesResources.into_new_overload, allOccurrences: false, IntroduceParameterCodeActionKind.Overload)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction( FeaturesResources.into_new_overload, allOccurrences: true, IntroduceParameterCodeActionKind.Overload)); } } return (actionsBuilder.ToImmutableAndClear(), actionsBuilderAllOccurrences.ToImmutableAndClear()); // Local function to create a code action with more ease MyCodeAction CreateNewCodeAction(string actionName, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction) { return new MyCodeAction(actionName, c => IntroduceParameterAsync( document, expression, methodSymbol, containingMethod, allOccurrences, selectedCodeAction, c)); } } /// <summary> /// Determines if the expression is something that should have code actions displayed for it. /// Depends upon the identifiers in the expression mapping back to parameters. /// Does not handle params parameters. /// </summary> private static async Task<(bool shouldDisplay, bool containsClassExpression)> ShouldExpressionDisplayCodeActionAsync( Document document, TExpressionSyntax expression, CancellationToken cancellationToken) { var variablesInExpression = expression.DescendantNodes(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var variable in variablesInExpression) { var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol; // If the expression contains locals or range variables then we do not want to offer // code actions since there will be errors at call sites. if (symbol is IRangeVariableSymbol or ILocalSymbol) { return (false, false); } if (symbol is IParameterSymbol parameter) { // We do not want to offer code actions if the expressions contains references // to params parameters because it is difficult to know what is being referenced // at the callsites. if (parameter.IsParams) { return (false, false); } } } // If expression contains this or base keywords, implicitly or explicitly, // then we do not want to refactor call sites that are not overloads/trampolines // because we do not know if the class specific information is available in other documents. var operation = semanticModel.GetOperation(expression, cancellationToken); var containsClassSpecificStatement = false; if (operation is not null) { containsClassSpecificStatement = operation.Descendants().Any(op => op.Kind == OperationKind.InstanceReference); } return (true, containsClassSpecificStatement); } /// <summary> /// Introduces a new parameter and refactors all the call sites based on the selected code action. /// </summary> private async Task<Solution> IntroduceParameterAsync(Document originalDocument, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction, CancellationToken cancellationToken) { var methodCallSites = await FindCallSitesAsync(originalDocument, methodSymbol, cancellationToken).ConfigureAwait(false); var modifiedSolution = originalDocument.Project.Solution; var rewriter = new IntroduceParameterDocumentRewriter(this, originalDocument, expression, methodSymbol, containingMethod, selectedCodeAction, allOccurrences); foreach (var (project, projectCallSites) in methodCallSites.GroupBy(kvp => kvp.Key.Project)) { var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var (document, invocations) in projectCallSites) { var newRoot = await rewriter.RewriteDocumentAsync(compilation, document, invocations, cancellationToken).ConfigureAwait(false); modifiedSolution = modifiedSolution.WithDocumentSyntaxRoot(originalDocument.Id, newRoot); } } return modifiedSolution; } /// <summary> /// Locates all the call sites of the method that introduced the parameter /// </summary> protected static async Task<Dictionary<Document, List<SyntaxNode>>> FindCallSitesAsync( Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken) { var methodCallSites = new Dictionary<Document, List<SyntaxNode>>(); var progress = new StreamingProgressCollector(); await SymbolFinder.FindReferencesAsync( methodSymbol, document.Project.Solution, progress, documents: null, FindReferencesSearchOptions.Default, cancellationToken).ConfigureAwait(false); var referencedSymbols = progress.GetReferencedSymbols(); // Ordering by descending to sort invocations by starting span to account for nested invocations var referencedLocations = referencedSymbols.SelectMany(referencedSymbol => referencedSymbol.Locations) .Distinct().Where(reference => !reference.IsImplicit) .OrderByDescending(reference => reference.Location.SourceSpan.Start); // Adding the original document to ensure that it will be seen again when processing the call sites // in order to update the original expression and containing method. methodCallSites.Add(document, new List<SyntaxNode>()); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var refLocation in referencedLocations) { // Does not support cross-language references currently if (refLocation.Document.Project.Language == document.Project.Language) { var reference = refLocation.Location.FindNode(cancellationToken).GetRequiredParent(); if (reference is not (TObjectCreationExpressionSyntax or TInvocationExpressionSyntax)) { reference = reference.GetRequiredParent(); } // Only adding items that are of type InvocationExpressionSyntax or TObjectCreationExpressionSyntax var invocationOrCreation = reference as TObjectCreationExpressionSyntax ?? (SyntaxNode?)(reference as TInvocationExpressionSyntax); if (invocationOrCreation is null) { continue; } if (!methodCallSites.TryGetValue(refLocation.Document, out var list)) { list = new List<SyntaxNode>(); methodCallSites.Add(refLocation.Document, list); } list.Add(invocationOrCreation); } } return methodCallSites; } private class MyCodeAction : SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } private enum IntroduceParameterCodeActionKind { Refactor, Trampoline, Overload } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/LabelSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal sealed class LabelSymbolReferenceFinder : AbstractMemberScopedReferenceFinder<ILabelSymbol> { protected override Func<SyntaxToken, bool> GetTokensMatchFunction(ISyntaxFactsService syntaxFacts, string name) { // Labels in VB can actually be numeric literals. Wacky. return t => IdentifiersMatch(syntaxFacts, name, t) || syntaxFacts.IsLiteral(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. using System; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal sealed class LabelSymbolReferenceFinder : AbstractMemberScopedReferenceFinder<ILabelSymbol> { protected override Func<SyntaxToken, bool> GetTokensMatchFunction(ISyntaxFactsService syntaxFacts, string name) { // Labels in VB can actually be numeric literals. Wacky. return t => IdentifiersMatch(syntaxFacts, name, t) || syntaxFacts.IsLiteral(t); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Tools/ExternalAccess/FSharp/Internal/Editor/Implementation/Debugging/FSharpLanguageDebugInfoService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor.Implementation.Debugging { [Shared] [ExportLanguageService(typeof(ILanguageDebugInfoService), LanguageNames.FSharp)] internal class FSharpLanguageDebugInfoService : ILanguageDebugInfoService { private readonly IFSharpLanguageDebugInfoService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpLanguageDebugInfoService(IFSharpLanguageDebugInfoService service) { _service = service; } public async Task<DebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _service.GetDataTipInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; public async Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _service.GetLocationInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor.Implementation.Debugging { [Shared] [ExportLanguageService(typeof(ILanguageDebugInfoService), LanguageNames.FSharp)] internal class FSharpLanguageDebugInfoService : ILanguageDebugInfoService { private readonly IFSharpLanguageDebugInfoService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpLanguageDebugInfoService(IFSharpLanguageDebugInfoService service) { _service = service; } public async Task<DebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _service.GetDataTipInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; public async Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _service.GetLocationInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Core/Portable/SourceFileResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Resolves references to source files specified in source code. /// </summary> public class SourceFileResolver : SourceReferenceResolver, IEquatable<SourceFileResolver> { public static SourceFileResolver Default { get; } = new SourceFileResolver(ImmutableArray<string>.Empty, baseDirectory: null); private readonly string? _baseDirectory; private readonly ImmutableArray<string> _searchPaths; private readonly ImmutableArray<KeyValuePair<string, string>> _pathMap; public SourceFileResolver(IEnumerable<string> searchPaths, string? baseDirectory) : this(searchPaths.AsImmutableOrNull(), baseDirectory) { } public SourceFileResolver(ImmutableArray<string> searchPaths, string? baseDirectory) : this(searchPaths, baseDirectory, ImmutableArray<KeyValuePair<string, string>>.Empty) { } public SourceFileResolver( ImmutableArray<string> searchPaths, string? baseDirectory, ImmutableArray<KeyValuePair<string, string>> pathMap) { if (searchPaths.IsDefault) { throw new ArgumentNullException(nameof(searchPaths)); } if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute) { throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(baseDirectory)); } _baseDirectory = baseDirectory; _searchPaths = searchPaths; // The previous public API required paths to not end with a path separator. // This broke handling of root paths (e.g. "/" cannot be represented), so // the new requirement is for paths to always end with a path separator. // However, because this is a public API, both conventions must be allowed, // so normalize the paths here (instead of enforcing end-with-sep). if (!pathMap.IsDefaultOrEmpty) { var pathMapBuilder = ArrayBuilder<KeyValuePair<string, string>>.GetInstance(pathMap.Length); foreach (var (key, value) in pathMap) { if (key == null || key.Length == 0) { throw new ArgumentException(CodeAnalysisResources.EmptyKeyInPathMap, nameof(pathMap)); } if (value == null) { throw new ArgumentException(CodeAnalysisResources.NullValueInPathMap, nameof(pathMap)); } var normalizedKey = PathUtilities.EnsureTrailingSeparator(key); var normalizedValue = PathUtilities.EnsureTrailingSeparator(value); pathMapBuilder.Add(new KeyValuePair<string, string>(normalizedKey, normalizedValue)); } _pathMap = pathMapBuilder.ToImmutableAndFree(); } else { _pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; } } public string? BaseDirectory => _baseDirectory; public ImmutableArray<string> SearchPaths => _searchPaths; public ImmutableArray<KeyValuePair<string, string>> PathMap => _pathMap; public override string? NormalizePath(string path, string? baseFilePath) { string? normalizedPath = FileUtilities.NormalizeRelativePath(path, baseFilePath, _baseDirectory); return (normalizedPath == null || _pathMap.IsDefaultOrEmpty) ? normalizedPath : PathUtilities.NormalizePathPrefix(normalizedPath, _pathMap); } public override string? ResolveReference(string path, string? baseFilePath) { string? resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory, _searchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } public override Stream OpenRead(string resolvedPath) { CompilerPathUtilities.RequireAbsolutePath(resolvedPath, nameof(resolvedPath)); return FileUtilities.OpenRead(resolvedPath); } protected virtual bool FileExists([NotNullWhen(true)] string? resolvedPath) { return File.Exists(resolvedPath); } public override bool Equals(object? obj) { // Explicitly check that we're not comparing against a derived type if (obj == null || GetType() != obj.GetType()) { return false; } return Equals((SourceFileResolver)obj); } public bool Equals(SourceFileResolver? other) { if (other is null) { return false; } return string.Equals(_baseDirectory, other._baseDirectory, StringComparison.Ordinal) && _searchPaths.SequenceEqual(other._searchPaths, StringComparer.Ordinal) && _pathMap.SequenceEqual(other._pathMap); } public override int GetHashCode() { return Hash.Combine(_baseDirectory != null ? StringComparer.Ordinal.GetHashCode(_baseDirectory) : 0, Hash.Combine(Hash.CombineValues(_searchPaths, StringComparer.Ordinal), Hash.CombineValues(_pathMap))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Resolves references to source files specified in source code. /// </summary> public class SourceFileResolver : SourceReferenceResolver, IEquatable<SourceFileResolver> { public static SourceFileResolver Default { get; } = new SourceFileResolver(ImmutableArray<string>.Empty, baseDirectory: null); private readonly string? _baseDirectory; private readonly ImmutableArray<string> _searchPaths; private readonly ImmutableArray<KeyValuePair<string, string>> _pathMap; public SourceFileResolver(IEnumerable<string> searchPaths, string? baseDirectory) : this(searchPaths.AsImmutableOrNull(), baseDirectory) { } public SourceFileResolver(ImmutableArray<string> searchPaths, string? baseDirectory) : this(searchPaths, baseDirectory, ImmutableArray<KeyValuePair<string, string>>.Empty) { } public SourceFileResolver( ImmutableArray<string> searchPaths, string? baseDirectory, ImmutableArray<KeyValuePair<string, string>> pathMap) { if (searchPaths.IsDefault) { throw new ArgumentNullException(nameof(searchPaths)); } if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute) { throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(baseDirectory)); } _baseDirectory = baseDirectory; _searchPaths = searchPaths; // The previous public API required paths to not end with a path separator. // This broke handling of root paths (e.g. "/" cannot be represented), so // the new requirement is for paths to always end with a path separator. // However, because this is a public API, both conventions must be allowed, // so normalize the paths here (instead of enforcing end-with-sep). if (!pathMap.IsDefaultOrEmpty) { var pathMapBuilder = ArrayBuilder<KeyValuePair<string, string>>.GetInstance(pathMap.Length); foreach (var (key, value) in pathMap) { if (key == null || key.Length == 0) { throw new ArgumentException(CodeAnalysisResources.EmptyKeyInPathMap, nameof(pathMap)); } if (value == null) { throw new ArgumentException(CodeAnalysisResources.NullValueInPathMap, nameof(pathMap)); } var normalizedKey = PathUtilities.EnsureTrailingSeparator(key); var normalizedValue = PathUtilities.EnsureTrailingSeparator(value); pathMapBuilder.Add(new KeyValuePair<string, string>(normalizedKey, normalizedValue)); } _pathMap = pathMapBuilder.ToImmutableAndFree(); } else { _pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; } } public string? BaseDirectory => _baseDirectory; public ImmutableArray<string> SearchPaths => _searchPaths; public ImmutableArray<KeyValuePair<string, string>> PathMap => _pathMap; public override string? NormalizePath(string path, string? baseFilePath) { string? normalizedPath = FileUtilities.NormalizeRelativePath(path, baseFilePath, _baseDirectory); return (normalizedPath == null || _pathMap.IsDefaultOrEmpty) ? normalizedPath : PathUtilities.NormalizePathPrefix(normalizedPath, _pathMap); } public override string? ResolveReference(string path, string? baseFilePath) { string? resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory, _searchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } public override Stream OpenRead(string resolvedPath) { CompilerPathUtilities.RequireAbsolutePath(resolvedPath, nameof(resolvedPath)); return FileUtilities.OpenRead(resolvedPath); } protected virtual bool FileExists([NotNullWhen(true)] string? resolvedPath) { return File.Exists(resolvedPath); } public override bool Equals(object? obj) { // Explicitly check that we're not comparing against a derived type if (obj == null || GetType() != obj.GetType()) { return false; } return Equals((SourceFileResolver)obj); } public bool Equals(SourceFileResolver? other) { if (other is null) { return false; } return string.Equals(_baseDirectory, other._baseDirectory, StringComparison.Ordinal) && _searchPaths.SequenceEqual(other._searchPaths, StringComparer.Ordinal) && _pathMap.SequenceEqual(other._pathMap); } public override int GetHashCode() { return Hash.Combine(_baseDirectory != null ? StringComparer.Ordinal.GetHashCode(_baseDirectory) : 0, Hash.Combine(Hash.CombineValues(_searchPaths, StringComparer.Ordinal), Hash.CombineValues(_pathMap))); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/TableDataSource/Suppression/VisualStudioDiagnosticListTableCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.ComponentModel.Design; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes.Configuration; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Suppression; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(VisualStudioDiagnosticListTableCommandHandler))] internal partial class VisualStudioDiagnosticListTableCommandHandler { private readonly VisualStudioWorkspace _workspace; private readonly VisualStudioSuppressionFixService _suppressionFixService; private readonly VisualStudioDiagnosticListSuppressionStateService _suppressionStateService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ICodeActionEditHandlerService _editHandlerService; private readonly IWpfTableControl _tableControl; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDiagnosticListTableCommandHandler( SVsServiceProvider serviceProvider, VisualStudioWorkspace workspace, IVisualStudioSuppressionFixService suppressionFixService, IVisualStudioDiagnosticListSuppressionStateService suppressionStateService, IUIThreadOperationExecutor uiThreadOperationExecutor, IDiagnosticAnalyzerService diagnosticService, ICodeActionEditHandlerService editHandlerService) { _workspace = workspace; _suppressionFixService = (VisualStudioSuppressionFixService)suppressionFixService; _suppressionStateService = (VisualStudioDiagnosticListSuppressionStateService)suppressionStateService; _uiThreadOperationExecutor = uiThreadOperationExecutor; _diagnosticService = diagnosticService; _editHandlerService = editHandlerService; var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList; _tableControl = errorList?.TableControl; } public void Initialize(IServiceProvider serviceProvider) { // Add command handlers for bulk suppression commands. var menuCommandService = (IMenuCommandService)serviceProvider.GetService(typeof(IMenuCommandService)); if (menuCommandService != null) { AddErrorListSetSeverityMenuHandlers(menuCommandService); // The Add/Remove suppression(s) have been moved to the VS code analysis layer, so we don't add the commands here. // TODO: Figure out how to access menu commands registered by CodeAnalysisPackage and // add the commands here if we cannot find the new command(s) in the code analysis layer. // AddSuppressionsCommandHandlers(menuCommandService); } } private void AddErrorListSetSeverityMenuHandlers(IMenuCommandService menuCommandService) { AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeveritySubMenu, delegate { }, OnErrorListSetSeveritySubMenuStatus); // Severity menu items AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityDefault, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityError, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityWarning, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityInfo, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityHidden, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityNone, SetSeverityHandler, delegate { }); } /// <summary> /// Add a command handler and status query handler for a menu item /// </summary> private static OleMenuCommand AddCommand( IMenuCommandService menuCommandService, int commandId, EventHandler invokeHandler, EventHandler beforeQueryStatus) { var commandIdWithGroupId = new CommandID(Guids.RoslynGroupId, commandId); var command = new OleMenuCommand(invokeHandler, delegate { }, beforeQueryStatus, commandIdWithGroupId); menuCommandService.AddCommand(command); return command; } private void OnAddSuppressionsStatus(object sender, EventArgs e) { var command = sender as MenuCommand; command.Visible = _suppressionStateService.CanSuppressSelectedEntries; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void OnRemoveSuppressionsStatus(object sender, EventArgs e) { var command = sender as MenuCommand; command.Visible = _suppressionStateService.CanRemoveSuppressionsSelectedEntries; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void OnAddSuppressionsInSourceStatus(object sender, EventArgs e) { var command = sender as MenuCommand; command.Visible = _suppressionStateService.CanSuppressSelectedEntriesInSource; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void OnAddSuppressionsInSuppressionFileStatus(object sender, EventArgs e) { var command = sender as MenuCommand; command.Visible = _suppressionStateService.CanSuppressSelectedEntriesInSuppressionFiles; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void OnAddSuppressionsInSource(object sender, EventArgs e) => _suppressionFixService.AddSuppressions(selectedErrorListEntriesOnly: true, suppressInSource: true, projectHierarchyOpt: null); private void OnAddSuppressionsInSuppressionFile(object sender, EventArgs e) => _suppressionFixService.AddSuppressions(selectedErrorListEntriesOnly: true, suppressInSource: false, projectHierarchyOpt: null); private void OnRemoveSuppressions(object sender, EventArgs e) => _suppressionFixService.RemoveSuppressions(selectedErrorListEntriesOnly: true, projectHierarchyOpt: null); private void OnErrorListSetSeveritySubMenuStatus(object sender, EventArgs e) { // For now, we only enable the Set severity menu when a single configurable diagnostic is selected in the error list // and we can update/create an editorconfig file for the configuration entry. // In future, we can enable support for configuring in presence of multi-selection. var command = (MenuCommand)sender; var selectedEntry = TryGetSingleSelectedEntry(); command.Visible = selectedEntry != null && !SuppressionHelpers.IsNotConfigurableDiagnostic(selectedEntry) && TryGetPathToAnalyzerConfigDoc(selectedEntry, out _) != null; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void SetSeverityHandler(object sender, EventArgs args) { var selectedItem = (MenuCommand)sender; var reportDiagnostic = TryMapSelectedItemToReportDiagnostic(selectedItem); if (reportDiagnostic == null) { return; } var selectedDiagnostic = TryGetSingleSelectedEntry(); if (selectedDiagnostic == null) { return; } var pathToAnalyzerConfigDoc = TryGetPathToAnalyzerConfigDoc(selectedDiagnostic, out var project); if (pathToAnalyzerConfigDoc != null) { var result = _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Updating_severity, defaultDescription: ServicesVSResources.Updating_severity, allowCancellation: true, showProgress: true, action: context => { var newSolution = ConfigureSeverityAsync(context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken); var operations = ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(newSolution)); var scope = context.AddScope(allowCancellation: true, ServicesVSResources.Updating_severity); _editHandlerService.Apply( _workspace, fromDocument: null, operations: operations, title: ServicesVSResources.Updating_severity, progressTracker: new UIThreadOperationContextProgressTracker(scope), cancellationToken: context.UserCancellationToken); }); if (result == UIThreadOperationStatus.Completed && selectedDiagnostic.DocumentId != null) { // Kick off diagnostic re-analysis for affected document so that the configured diagnostic gets refreshed. Task.Run(() => { _diagnosticService.Reanalyze(_workspace, documentIds: SpecializedCollections.SingletonEnumerable(selectedDiagnostic.DocumentId), highPriority: true); }); } } return; // Local functions. async System.Threading.Tasks.Task<Solution> ConfigureSeverityAsync(CancellationToken cancellationToken) { var diagnostic = await selectedDiagnostic.ToDiagnosticAsync(project, cancellationToken).ConfigureAwait(false); return await ConfigurationUpdater.ConfigureSeverityAsync(reportDiagnostic.Value, diagnostic, project, cancellationToken).ConfigureAwait(false); } } private DiagnosticData TryGetSingleSelectedEntry() { if (_tableControl?.SelectedEntries.Count() != 1) { return null; } if (!_tableControl.SelectedEntry.TryGetSnapshot(out var snapshot, out var index) || snapshot is not AbstractTableEntriesSnapshot<DiagnosticTableItem> roslynSnapshot) { return null; } return roslynSnapshot.GetItem(index)?.Data; } private string TryGetPathToAnalyzerConfigDoc(DiagnosticData selectedDiagnostic, out Project project) { project = _workspace.CurrentSolution.GetProject(selectedDiagnostic.ProjectId); return project?.TryGetAnalyzerConfigPathForProjectConfiguration(); } private static ReportDiagnostic? TryMapSelectedItemToReportDiagnostic(MenuCommand selectedItem) { if (selectedItem.CommandID.Guid == Guids.RoslynGroupId) { return selectedItem.CommandID.ID switch { ID.RoslynCommands.ErrorListSetSeverityDefault => ReportDiagnostic.Default, ID.RoslynCommands.ErrorListSetSeverityError => ReportDiagnostic.Error, ID.RoslynCommands.ErrorListSetSeverityWarning => ReportDiagnostic.Warn, ID.RoslynCommands.ErrorListSetSeverityInfo => ReportDiagnostic.Info, ID.RoslynCommands.ErrorListSetSeverityHidden => ReportDiagnostic.Hidden, ID.RoslynCommands.ErrorListSetSeverityNone => ReportDiagnostic.Suppress, _ => (ReportDiagnostic?)null }; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.ComponentModel.Design; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes.Configuration; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Suppression; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(VisualStudioDiagnosticListTableCommandHandler))] internal partial class VisualStudioDiagnosticListTableCommandHandler { private readonly VisualStudioWorkspace _workspace; private readonly VisualStudioSuppressionFixService _suppressionFixService; private readonly VisualStudioDiagnosticListSuppressionStateService _suppressionStateService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ICodeActionEditHandlerService _editHandlerService; private readonly IWpfTableControl _tableControl; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDiagnosticListTableCommandHandler( SVsServiceProvider serviceProvider, VisualStudioWorkspace workspace, IVisualStudioSuppressionFixService suppressionFixService, IVisualStudioDiagnosticListSuppressionStateService suppressionStateService, IUIThreadOperationExecutor uiThreadOperationExecutor, IDiagnosticAnalyzerService diagnosticService, ICodeActionEditHandlerService editHandlerService) { _workspace = workspace; _suppressionFixService = (VisualStudioSuppressionFixService)suppressionFixService; _suppressionStateService = (VisualStudioDiagnosticListSuppressionStateService)suppressionStateService; _uiThreadOperationExecutor = uiThreadOperationExecutor; _diagnosticService = diagnosticService; _editHandlerService = editHandlerService; var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList; _tableControl = errorList?.TableControl; } public void Initialize(IServiceProvider serviceProvider) { // Add command handlers for bulk suppression commands. var menuCommandService = (IMenuCommandService)serviceProvider.GetService(typeof(IMenuCommandService)); if (menuCommandService != null) { AddErrorListSetSeverityMenuHandlers(menuCommandService); // The Add/Remove suppression(s) have been moved to the VS code analysis layer, so we don't add the commands here. // TODO: Figure out how to access menu commands registered by CodeAnalysisPackage and // add the commands here if we cannot find the new command(s) in the code analysis layer. // AddSuppressionsCommandHandlers(menuCommandService); } } private void AddErrorListSetSeverityMenuHandlers(IMenuCommandService menuCommandService) { AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeveritySubMenu, delegate { }, OnErrorListSetSeveritySubMenuStatus); // Severity menu items AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityDefault, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityError, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityWarning, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityInfo, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityHidden, SetSeverityHandler, delegate { }); AddCommand(menuCommandService, ID.RoslynCommands.ErrorListSetSeverityNone, SetSeverityHandler, delegate { }); } /// <summary> /// Add a command handler and status query handler for a menu item /// </summary> private static OleMenuCommand AddCommand( IMenuCommandService menuCommandService, int commandId, EventHandler invokeHandler, EventHandler beforeQueryStatus) { var commandIdWithGroupId = new CommandID(Guids.RoslynGroupId, commandId); var command = new OleMenuCommand(invokeHandler, delegate { }, beforeQueryStatus, commandIdWithGroupId); menuCommandService.AddCommand(command); return command; } private void OnAddSuppressionsStatus(object sender, EventArgs e) { var command = sender as MenuCommand; command.Visible = _suppressionStateService.CanSuppressSelectedEntries; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void OnRemoveSuppressionsStatus(object sender, EventArgs e) { var command = sender as MenuCommand; command.Visible = _suppressionStateService.CanRemoveSuppressionsSelectedEntries; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void OnAddSuppressionsInSourceStatus(object sender, EventArgs e) { var command = sender as MenuCommand; command.Visible = _suppressionStateService.CanSuppressSelectedEntriesInSource; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void OnAddSuppressionsInSuppressionFileStatus(object sender, EventArgs e) { var command = sender as MenuCommand; command.Visible = _suppressionStateService.CanSuppressSelectedEntriesInSuppressionFiles; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void OnAddSuppressionsInSource(object sender, EventArgs e) => _suppressionFixService.AddSuppressions(selectedErrorListEntriesOnly: true, suppressInSource: true, projectHierarchyOpt: null); private void OnAddSuppressionsInSuppressionFile(object sender, EventArgs e) => _suppressionFixService.AddSuppressions(selectedErrorListEntriesOnly: true, suppressInSource: false, projectHierarchyOpt: null); private void OnRemoveSuppressions(object sender, EventArgs e) => _suppressionFixService.RemoveSuppressions(selectedErrorListEntriesOnly: true, projectHierarchyOpt: null); private void OnErrorListSetSeveritySubMenuStatus(object sender, EventArgs e) { // For now, we only enable the Set severity menu when a single configurable diagnostic is selected in the error list // and we can update/create an editorconfig file for the configuration entry. // In future, we can enable support for configuring in presence of multi-selection. var command = (MenuCommand)sender; var selectedEntry = TryGetSingleSelectedEntry(); command.Visible = selectedEntry != null && !SuppressionHelpers.IsNotConfigurableDiagnostic(selectedEntry) && TryGetPathToAnalyzerConfigDoc(selectedEntry, out _) != null; command.Enabled = command.Visible && !KnownUIContexts.SolutionBuildingContext.IsActive; } private void SetSeverityHandler(object sender, EventArgs args) { var selectedItem = (MenuCommand)sender; var reportDiagnostic = TryMapSelectedItemToReportDiagnostic(selectedItem); if (reportDiagnostic == null) { return; } var selectedDiagnostic = TryGetSingleSelectedEntry(); if (selectedDiagnostic == null) { return; } var pathToAnalyzerConfigDoc = TryGetPathToAnalyzerConfigDoc(selectedDiagnostic, out var project); if (pathToAnalyzerConfigDoc != null) { var result = _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Updating_severity, defaultDescription: ServicesVSResources.Updating_severity, allowCancellation: true, showProgress: true, action: context => { var newSolution = ConfigureSeverityAsync(context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken); var operations = ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(newSolution)); var scope = context.AddScope(allowCancellation: true, ServicesVSResources.Updating_severity); _editHandlerService.Apply( _workspace, fromDocument: null, operations: operations, title: ServicesVSResources.Updating_severity, progressTracker: new UIThreadOperationContextProgressTracker(scope), cancellationToken: context.UserCancellationToken); }); if (result == UIThreadOperationStatus.Completed && selectedDiagnostic.DocumentId != null) { // Kick off diagnostic re-analysis for affected document so that the configured diagnostic gets refreshed. Task.Run(() => { _diagnosticService.Reanalyze(_workspace, documentIds: SpecializedCollections.SingletonEnumerable(selectedDiagnostic.DocumentId), highPriority: true); }); } } return; // Local functions. async System.Threading.Tasks.Task<Solution> ConfigureSeverityAsync(CancellationToken cancellationToken) { var diagnostic = await selectedDiagnostic.ToDiagnosticAsync(project, cancellationToken).ConfigureAwait(false); return await ConfigurationUpdater.ConfigureSeverityAsync(reportDiagnostic.Value, diagnostic, project, cancellationToken).ConfigureAwait(false); } } private DiagnosticData TryGetSingleSelectedEntry() { if (_tableControl?.SelectedEntries.Count() != 1) { return null; } if (!_tableControl.SelectedEntry.TryGetSnapshot(out var snapshot, out var index) || snapshot is not AbstractTableEntriesSnapshot<DiagnosticTableItem> roslynSnapshot) { return null; } return roslynSnapshot.GetItem(index)?.Data; } private string TryGetPathToAnalyzerConfigDoc(DiagnosticData selectedDiagnostic, out Project project) { project = _workspace.CurrentSolution.GetProject(selectedDiagnostic.ProjectId); return project?.TryGetAnalyzerConfigPathForProjectConfiguration(); } private static ReportDiagnostic? TryMapSelectedItemToReportDiagnostic(MenuCommand selectedItem) { if (selectedItem.CommandID.Guid == Guids.RoslynGroupId) { return selectedItem.CommandID.ID switch { ID.RoslynCommands.ErrorListSetSeverityDefault => ReportDiagnostic.Default, ID.RoslynCommands.ErrorListSetSeverityError => ReportDiagnostic.Error, ID.RoslynCommands.ErrorListSetSeverityWarning => ReportDiagnostic.Warn, ID.RoslynCommands.ErrorListSetSeverityInfo => ReportDiagnostic.Info, ID.RoslynCommands.ErrorListSetSeverityHidden => ReportDiagnostic.Hidden, ID.RoslynCommands.ErrorListSetSeverityNone => ReportDiagnostic.Suppress, _ => (ReportDiagnostic?)null }; } return null; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/EditorFeatures/CSharpTest2/Recommendations/SealedKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 SealedKeywordRecommenderTests : 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 TestAfterMethodInClass() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFieldInClass() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyInClass() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [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;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global 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 TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task 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 TestNotAfterStaticInternal() => await VerifyAbsenceAsync(@"static internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternalStatic() => await VerifyAbsenceAsync(@"internal static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidInternal() => await VerifyAbsenceAsync(@"virtual internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [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 $$"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticInInterface() { await VerifyKeywordAsync(@"interface C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { abstract $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedOverride() { await VerifyKeywordAsync( @"class C { override $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessibility() { await VerifyAbsenceAsync( @"class C { int Goo { get; protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterInternal() { await VerifyAbsenceAsync( @"class C { int Goo { get; internal $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 SealedKeywordRecommenderTests : 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 TestAfterMethodInClass() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFieldInClass() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyInClass() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [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;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global 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 TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task 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 TestNotAfterStaticInternal() => await VerifyAbsenceAsync(@"static internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternalStatic() => await VerifyAbsenceAsync(@"internal static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidInternal() => await VerifyAbsenceAsync(@"virtual internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [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 $$"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticInInterface() { await VerifyKeywordAsync(@"interface C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { abstract $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedOverride() { await VerifyKeywordAsync( @"class C { override $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessibility() { await VerifyAbsenceAsync( @"class C { int Goo { get; protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterInternal() { await VerifyAbsenceAsync( @"class C { int Goo { get; internal $$"); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/LongTypeFormInSignature.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // 1) csc /target:library LongTypeFormInSignature.cs // 2) open in a binary editor and replace "Attribute" with "String\0\0\0" and "DateTime" with "Double\0\0" (the only occurrence should be in the #String heap). public class C { public static System.Attribute RT() { return null; } public static System.DateTime VT() { return default(System.DateTime); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // 1) csc /target:library LongTypeFormInSignature.cs // 2) open in a binary editor and replace "Attribute" with "String\0\0\0" and "DateTime" with "Double\0\0" (the only occurrence should be in the #String heap). public class C { public static System.Attribute RT() { return null; } public static System.DateTime VT() { return default(System.DateTime); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Core/Portable/FileSystem/RelativePathResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; using System.IO; namespace Microsoft.CodeAnalysis { internal class RelativePathResolver : IEquatable<RelativePathResolver> { public ImmutableArray<string> SearchPaths { get; } public string BaseDirectory { get; } /// <summary> /// Initializes a new instance of the <see cref="RelativePathResolver"/> class. /// </summary> /// <param name="searchPaths">An ordered set of fully qualified /// paths which are searched when resolving assembly names.</param> /// <param name="baseDirectory">Directory used when resolving relative paths.</param> public RelativePathResolver(ImmutableArray<string> searchPaths, string baseDirectory) { Debug.Assert(searchPaths.All(PathUtilities.IsAbsolute)); Debug.Assert(baseDirectory == null || PathUtilities.GetPathKind(baseDirectory) == PathKind.Absolute); SearchPaths = searchPaths; BaseDirectory = baseDirectory; } public string ResolvePath(string reference, string baseFilePath) { string resolvedPath = FileUtilities.ResolveRelativePath(reference, baseFilePath, BaseDirectory, SearchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } protected virtual bool FileExists(string fullPath) { Debug.Assert(fullPath != null); Debug.Assert(PathUtilities.IsAbsolute(fullPath)); return File.Exists(fullPath); } public RelativePathResolver WithSearchPaths(ImmutableArray<string> searchPaths) => new(searchPaths, BaseDirectory); public RelativePathResolver WithBaseDirectory(string baseDirectory) => new(SearchPaths, baseDirectory); public bool Equals(RelativePathResolver other) => BaseDirectory == other.BaseDirectory && SearchPaths.SequenceEqual(other.SearchPaths); public override int GetHashCode() => Hash.Combine(BaseDirectory, Hash.CombineValues(SearchPaths)); public override bool Equals(object obj) => Equals(obj as RelativePathResolver); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; using System.IO; namespace Microsoft.CodeAnalysis { internal class RelativePathResolver : IEquatable<RelativePathResolver> { public ImmutableArray<string> SearchPaths { get; } public string BaseDirectory { get; } /// <summary> /// Initializes a new instance of the <see cref="RelativePathResolver"/> class. /// </summary> /// <param name="searchPaths">An ordered set of fully qualified /// paths which are searched when resolving assembly names.</param> /// <param name="baseDirectory">Directory used when resolving relative paths.</param> public RelativePathResolver(ImmutableArray<string> searchPaths, string baseDirectory) { Debug.Assert(searchPaths.All(PathUtilities.IsAbsolute)); Debug.Assert(baseDirectory == null || PathUtilities.GetPathKind(baseDirectory) == PathKind.Absolute); SearchPaths = searchPaths; BaseDirectory = baseDirectory; } public string ResolvePath(string reference, string baseFilePath) { string resolvedPath = FileUtilities.ResolveRelativePath(reference, baseFilePath, BaseDirectory, SearchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } protected virtual bool FileExists(string fullPath) { Debug.Assert(fullPath != null); Debug.Assert(PathUtilities.IsAbsolute(fullPath)); return File.Exists(fullPath); } public RelativePathResolver WithSearchPaths(ImmutableArray<string> searchPaths) => new(searchPaths, BaseDirectory); public RelativePathResolver WithBaseDirectory(string baseDirectory) => new(SearchPaths, baseDirectory); public bool Equals(RelativePathResolver other) => BaseDirectory == other.BaseDirectory && SearchPaths.SequenceEqual(other.SearchPaths); public override int GetHashCode() => Hash.Combine(BaseDirectory, Hash.CombineValues(SearchPaths)); public override bool Equals(object obj) => Equals(obj as RelativePathResolver); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/VisualStudio/Core/Def/EditorConfigSettings/Common/IEnumSettingViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal interface IEnumSettingViewModel { string[] GetValueDescriptions(); int GetValueIndex(); void ChangeProperty(string v); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal interface IEnumSettingViewModel { string[] GetValueDescriptions(); int GetValueIndex(); void ChangeProperty(string v); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Features/Core/Portable/Emit/CompilationOutputFiles.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal sealed class CompilationOutputFiles : CompilationOutputs { internal static readonly CompilationOutputFiles None = new(); public override string AssemblyDisplayPath => AssemblyFilePath; public override string PdbDisplayPath => PdbFilePath; public string PdbFilePath { get; } public string AssemblyFilePath { get; } public CompilationOutputFiles(string assemblyFilePath = null, string pdbFilePath = null) { if (assemblyFilePath != null) { CompilerPathUtilities.RequireAbsolutePath(assemblyFilePath, nameof(assemblyFilePath)); } if (pdbFilePath != null) { CompilerPathUtilities.RequireAbsolutePath(pdbFilePath, nameof(pdbFilePath)); } AssemblyFilePath = assemblyFilePath; PdbFilePath = pdbFilePath; } /// <summary> /// Opens an assembly file produced by the compiler (corresponds to OutputAssembly build task parameter). /// </summary> protected override Stream OpenAssemblyStream() => AssemblyFilePath != null ? FileUtilities.OpenRead(AssemblyFilePath) : null; /// <summary> /// Opens a PDB file produced by the compiler. /// Returns null if the compiler generated no PDB (the symbols might be embedded in the assembly). /// </summary> /// <remarks> /// The stream must be readable and seekable. /// </remarks> protected override Stream OpenPdbStream() => PdbFilePath != null ? FileUtilities.OpenRead(PdbFilePath) : 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.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal sealed class CompilationOutputFiles : CompilationOutputs { internal static readonly CompilationOutputFiles None = new(); public override string AssemblyDisplayPath => AssemblyFilePath; public override string PdbDisplayPath => PdbFilePath; public string PdbFilePath { get; } public string AssemblyFilePath { get; } public CompilationOutputFiles(string assemblyFilePath = null, string pdbFilePath = null) { if (assemblyFilePath != null) { CompilerPathUtilities.RequireAbsolutePath(assemblyFilePath, nameof(assemblyFilePath)); } if (pdbFilePath != null) { CompilerPathUtilities.RequireAbsolutePath(pdbFilePath, nameof(pdbFilePath)); } AssemblyFilePath = assemblyFilePath; PdbFilePath = pdbFilePath; } /// <summary> /// Opens an assembly file produced by the compiler (corresponds to OutputAssembly build task parameter). /// </summary> protected override Stream OpenAssemblyStream() => AssemblyFilePath != null ? FileUtilities.OpenRead(AssemblyFilePath) : null; /// <summary> /// Opens a PDB file produced by the compiler. /// Returns null if the compiler generated no PDB (the symbols might be embedded in the assembly). /// </summary> /// <remarks> /// The stream must be readable and seekable. /// </remarks> protected override Stream OpenPdbStream() => PdbFilePath != null ? FileUtilities.OpenRead(PdbFilePath) : null; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/EditorFeatures/Core/Extensibility/NavigationBar/INavigationBarItemService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor { internal interface INavigationBarItemService : ILanguageService { Task<ImmutableArray<NavigationBarItem>> GetItemsAsync(Document document, ITextVersion textVersion, CancellationToken cancellationToken); bool ShowItemGrayedIfNear(NavigationBarItem item); /// <summary> /// Returns <see langword="true"/> if navigation (or generation) happened. <see langword="false"/> otherwise. /// </summary> Task<bool> TryNavigateToItemAsync( Document document, NavigationBarItem item, ITextView view, ITextVersion textVersion, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor { internal interface INavigationBarItemService : ILanguageService { Task<ImmutableArray<NavigationBarItem>> GetItemsAsync(Document document, ITextVersion textVersion, CancellationToken cancellationToken); bool ShowItemGrayedIfNear(NavigationBarItem item); /// <summary> /// Returns <see langword="true"/> if navigation (or generation) happened. <see langword="false"/> otherwise. /// </summary> Task<bool> TryNavigateToItemAsync( Document document, NavigationBarItem item, ITextView view, ITextVersion textVersion, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Features/Core/Portable/Completion/MatchResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PatternMatching; using Roslyn.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; namespace Microsoft.CodeAnalysis.Completion { internal readonly struct MatchResult<TEditorCompletionItem> { public readonly RoslynCompletionItem RoslynCompletionItem; public readonly bool MatchedFilterText; // In certain cases, there'd be no match but we'd still set `MatchedFilterText` to true, // e.g. when the item is in MRU list. Therefore making this nullable. public readonly PatternMatch? PatternMatch; /// <summary> /// The actual editor completion item associated with this <see cref="RoslynCompletionItem"/> /// In VS for example, this is the associated VS async completion item. /// </summary> public readonly TEditorCompletionItem EditorCompletionItem; // We want to preserve the original alphabetical order for items with same pattern match score, // but `ArrayBuilder.Sort` we currently use isn't stable. So we have to add a monotonically increasing // integer to archieve this. private readonly int _indexInOriginalSortedOrder; public MatchResult( RoslynCompletionItem roslynCompletionItem, TEditorCompletionItem editorCompletionItem, bool matchedFilterText, PatternMatch? patternMatch, int index) { RoslynCompletionItem = roslynCompletionItem; EditorCompletionItem = editorCompletionItem; MatchedFilterText = matchedFilterText; PatternMatch = patternMatch; _indexInOriginalSortedOrder = index; } public static IComparer<MatchResult<TEditorCompletionItem>> SortingComparer => FilterResultSortingComparer.Instance; private class FilterResultSortingComparer : IComparer<MatchResult<TEditorCompletionItem>> { public static FilterResultSortingComparer Instance { get; } = new FilterResultSortingComparer(); // This comparison is used for sorting items in the completion list for the original sorting. public int Compare(MatchResult<TEditorCompletionItem> x, MatchResult<TEditorCompletionItem> y) { var matchX = x.PatternMatch; var matchY = y.PatternMatch; if (matchX.HasValue) { if (matchY.HasValue) { var ret = matchX.Value.CompareTo(matchY.Value); // We want to preserve the original order for items with same pattern match score. return ret == 0 ? x._indexInOriginalSortedOrder - y._indexInOriginalSortedOrder : ret; } return -1; } if (matchY.HasValue) { return 1; } return x._indexInOriginalSortedOrder - y._indexInOriginalSortedOrder; } } // This comparison is used in the deletion/backspace scenario for selecting best elements. public int CompareTo(MatchResult<TEditorCompletionItem> other, string filterText) => ComparerWithState.CompareTo(this, other, filterText, s_comparers); private static readonly ImmutableArray<Func<MatchResult<TEditorCompletionItem>, string, IComparable>> s_comparers = ImmutableArray.Create<Func<MatchResult<TEditorCompletionItem>, string, IComparable>>( // Prefer the item that matches a longer prefix of the filter text. (f, s) => f.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(s), // If there are "Abc" vs "abc", we should prefer the case typed by user. (f, s) => f.RoslynCompletionItem.FilterText.GetCaseSensitivePrefixLength(s), // If the lengths are the same, prefer the one with the higher match priority. // But only if it's an item that would have been hard selected. We don't want // to aggressively select an item that was only going to be softly offered. (f, s) => f.RoslynCompletionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection ? f.RoslynCompletionItem.Rules.MatchPriority : MatchPriority.Default, // Prefer Intellicode items. (f, s) => f.RoslynCompletionItem.IsPreferredItem()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PatternMatching; using Roslyn.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; namespace Microsoft.CodeAnalysis.Completion { internal readonly struct MatchResult<TEditorCompletionItem> { public readonly RoslynCompletionItem RoslynCompletionItem; public readonly bool MatchedFilterText; // In certain cases, there'd be no match but we'd still set `MatchedFilterText` to true, // e.g. when the item is in MRU list. Therefore making this nullable. public readonly PatternMatch? PatternMatch; /// <summary> /// The actual editor completion item associated with this <see cref="RoslynCompletionItem"/> /// In VS for example, this is the associated VS async completion item. /// </summary> public readonly TEditorCompletionItem EditorCompletionItem; // We want to preserve the original alphabetical order for items with same pattern match score, // but `ArrayBuilder.Sort` we currently use isn't stable. So we have to add a monotonically increasing // integer to archieve this. private readonly int _indexInOriginalSortedOrder; public MatchResult( RoslynCompletionItem roslynCompletionItem, TEditorCompletionItem editorCompletionItem, bool matchedFilterText, PatternMatch? patternMatch, int index) { RoslynCompletionItem = roslynCompletionItem; EditorCompletionItem = editorCompletionItem; MatchedFilterText = matchedFilterText; PatternMatch = patternMatch; _indexInOriginalSortedOrder = index; } public static IComparer<MatchResult<TEditorCompletionItem>> SortingComparer => FilterResultSortingComparer.Instance; private class FilterResultSortingComparer : IComparer<MatchResult<TEditorCompletionItem>> { public static FilterResultSortingComparer Instance { get; } = new FilterResultSortingComparer(); // This comparison is used for sorting items in the completion list for the original sorting. public int Compare(MatchResult<TEditorCompletionItem> x, MatchResult<TEditorCompletionItem> y) { var matchX = x.PatternMatch; var matchY = y.PatternMatch; if (matchX.HasValue) { if (matchY.HasValue) { var ret = matchX.Value.CompareTo(matchY.Value); // We want to preserve the original order for items with same pattern match score. return ret == 0 ? x._indexInOriginalSortedOrder - y._indexInOriginalSortedOrder : ret; } return -1; } if (matchY.HasValue) { return 1; } return x._indexInOriginalSortedOrder - y._indexInOriginalSortedOrder; } } // This comparison is used in the deletion/backspace scenario for selecting best elements. public int CompareTo(MatchResult<TEditorCompletionItem> other, string filterText) => ComparerWithState.CompareTo(this, other, filterText, s_comparers); private static readonly ImmutableArray<Func<MatchResult<TEditorCompletionItem>, string, IComparable>> s_comparers = ImmutableArray.Create<Func<MatchResult<TEditorCompletionItem>, string, IComparable>>( // Prefer the item that matches a longer prefix of the filter text. (f, s) => f.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(s), // If there are "Abc" vs "abc", we should prefer the case typed by user. (f, s) => f.RoslynCompletionItem.FilterText.GetCaseSensitivePrefixLength(s), // If the lengths are the same, prefer the one with the higher match priority. // But only if it's an item that would have been hard selected. We don't want // to aggressively select an item that was only going to be softly offered. (f, s) => f.RoslynCompletionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection ? f.RoslynCompletionItem.Rules.MatchPriority : MatchPriority.Default, // Prefer Intellicode items. (f, s) => f.RoslynCompletionItem.IsPreferredItem()); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/EditorFeatures/CSharpTest2/Recommendations/RegionKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 RegionKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 RegionKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/IProjectExistsUIContextProviderLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Host; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// Implemented by an language that wants a <see cref="UIContext"/> to be activated when there is a project of a given language in the workspace. /// </summary> internal interface IProjectExistsUIContextProviderLanguageService : ILanguageService { UIContext GetUIContext(); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Host; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// Implemented by an language that wants a <see cref="UIContext"/> to be activated when there is a project of a given language in the workspace. /// </summary> internal interface IProjectExistsUIContextProviderLanguageService : ILanguageService { UIContext GetUIContext(); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Test/Core/Platform/Desktop/TestHelpers.cs
// Licensed to the .NET Foundation under one or more 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 NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.Win32; using Basic.Reference.Assemblies; namespace Roslyn.Test.Utilities { public static class DesktopTestHelpers { public static IEnumerable<Type> GetAllTypesImplementingGivenInterface(Assembly assembly, Type interfaceType) { if (assembly == null || interfaceType == null || !interfaceType.IsInterface) { throw new ArgumentException("interfaceType is not an interface.", nameof(interfaceType)); } return assembly.GetTypes().Where((t) => { // simplest way to get types that implement mef type // we might need to actually check whether type export the interface type later if (t.IsAbstract) { return false; } var candidate = t.GetInterface(interfaceType.ToString()); return candidate != null && candidate.Equals(interfaceType); }).ToList(); } public static IEnumerable<Type> GetAllTypesSubclassingType(Assembly assembly, Type type) { if (assembly == null || type == null) { throw new ArgumentException("Invalid arguments"); } return (from t in assembly.GetTypes() where !t.IsAbstract where type.IsAssignableFrom(t) select t).ToList(); } public static TempFile CreateCSharpAnalyzerAssemblyWithTestAnalyzer(TempDirectory dir, string assemblyName) { var analyzerSource = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } }"; dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location); var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location); var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); dir.CopyFile(typeof(Memory<>).Assembly.Location); dir.CopyFile(typeof(System.Runtime.CompilerServices.Unsafe).Assembly.Location); var analyzerCompilation = CSharpCompilation.Create( assemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { NetStandard20.mscorlib, NetStandard20.netstandard, NetStandard20.SystemRuntime, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(analyzer.Path) }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); return dir.CreateFile(assemblyName + ".dll").WriteAllBytes(analyzerCompilation.EmitToArray()); } public static string? GetMSBuildDirectory() { var vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") ?? "14.0"; using (var key = Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{vsVersion}", false)) { if (key != null) { var toolsPath = key.GetValue("MSBuildToolsPath"); if (toolsPath != null) { return toolsPath.ToString(); } } } return null; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.Win32; using Basic.Reference.Assemblies; namespace Roslyn.Test.Utilities { public static class DesktopTestHelpers { public static IEnumerable<Type> GetAllTypesImplementingGivenInterface(Assembly assembly, Type interfaceType) { if (assembly == null || interfaceType == null || !interfaceType.IsInterface) { throw new ArgumentException("interfaceType is not an interface.", nameof(interfaceType)); } return assembly.GetTypes().Where((t) => { // simplest way to get types that implement mef type // we might need to actually check whether type export the interface type later if (t.IsAbstract) { return false; } var candidate = t.GetInterface(interfaceType.ToString()); return candidate != null && candidate.Equals(interfaceType); }).ToList(); } public static IEnumerable<Type> GetAllTypesSubclassingType(Assembly assembly, Type type) { if (assembly == null || type == null) { throw new ArgumentException("Invalid arguments"); } return (from t in assembly.GetTypes() where !t.IsAbstract where type.IsAssignableFrom(t) select t).ToList(); } public static TempFile CreateCSharpAnalyzerAssemblyWithTestAnalyzer(TempDirectory dir, string assemblyName) { var analyzerSource = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } }"; dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location); var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location); var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); dir.CopyFile(typeof(Memory<>).Assembly.Location); dir.CopyFile(typeof(System.Runtime.CompilerServices.Unsafe).Assembly.Location); var analyzerCompilation = CSharpCompilation.Create( assemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { NetStandard20.mscorlib, NetStandard20.netstandard, NetStandard20.SystemRuntime, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(analyzer.Path) }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); return dir.CreateFile(assemblyName + ".dll").WriteAllBytes(analyzerCompilation.EmitToArray()); } public static string? GetMSBuildDirectory() { var vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") ?? "14.0"; using (var key = Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{vsVersion}", false)) { if (key != null) { var toolsPath = key.GetValue("MSBuildToolsPath"); if (toolsPath != null) { return toolsPath.ToString(); } } } return null; } } } #endif
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Simplification/DoNotAllowVarAnnotation.cs
// Licensed to the .NET Foundation under one or more 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.Simplification { /// <summary> /// When applied to a SyntaxNode, prevents the simplifier from converting a type to 'var'. /// </summary> internal class DoNotAllowVarAnnotation { public static readonly SyntaxAnnotation Annotation = new(Kind); public const string Kind = "DoNotAllowVar"; } }
// Licensed to the .NET Foundation under one or more 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.Simplification { /// <summary> /// When applied to a SyntaxNode, prevents the simplifier from converting a type to 'var'. /// </summary> internal class DoNotAllowVarAnnotation { public static readonly SyntaxAnnotation Annotation = new(Kind); public const string Kind = "DoNotAllowVar"; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/ParametersWithoutNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; class Program { /// <summary> /// Compile and run this program to generate ParametersWithoutNames.dll /// </summary> static void Main() { var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ParametersWithoutNames"), AssemblyBuilderAccess.Save, new[] { new CustomAttributeBuilder(typeof(ImportedFromTypeLibAttribute).GetConstructor(new[] { typeof(string) }), new[] { "GeneralPIA.dll" }), new CustomAttributeBuilder(typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { "f9c2d51d-4f44-45f0-9eda-c9d599b58257" })}); var moduleBuilder = assemblyBuilder.DefineDynamicModule("ParametersWithoutNames", "ParametersWithoutNames.dll"); var typeBuilder = moduleBuilder.DefineType("I1", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Import | TypeAttributes.Interface); typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { "f9c2d51d-4f44-45f0-9eda-c9d599b58277" })); var methodBuilder = typeBuilder.DefineMethod("M1", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig, typeof(void), new[] { typeof(int), typeof(int), typeof(int) }); methodBuilder.DefineParameter(2, ParameterAttributes.Optional, null); methodBuilder.DefineParameter(3, ParameterAttributes.None, ""); typeBuilder.CreateType(); assemblyBuilder.Save(@"ParametersWithoutNames.dll"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; class Program { /// <summary> /// Compile and run this program to generate ParametersWithoutNames.dll /// </summary> static void Main() { var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ParametersWithoutNames"), AssemblyBuilderAccess.Save, new[] { new CustomAttributeBuilder(typeof(ImportedFromTypeLibAttribute).GetConstructor(new[] { typeof(string) }), new[] { "GeneralPIA.dll" }), new CustomAttributeBuilder(typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { "f9c2d51d-4f44-45f0-9eda-c9d599b58257" })}); var moduleBuilder = assemblyBuilder.DefineDynamicModule("ParametersWithoutNames", "ParametersWithoutNames.dll"); var typeBuilder = moduleBuilder.DefineType("I1", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Import | TypeAttributes.Interface); typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { "f9c2d51d-4f44-45f0-9eda-c9d599b58277" })); var methodBuilder = typeBuilder.DefineMethod("M1", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig, typeof(void), new[] { typeof(int), typeof(int), typeof(int) }); methodBuilder.DefineParameter(2, ParameterAttributes.Optional, null); methodBuilder.DefineParameter(3, ParameterAttributes.None, ""); typeBuilder.CreateType(); assemblyBuilder.Save(@"ParametersWithoutNames.dll"); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolDisplayFormats.cs
// Licensed to the .NET Foundation under one or more 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.Shared.Extensions { internal static class SymbolDisplayFormats { /// <summary> /// Standard format for displaying to the user. /// </summary> /// <remarks> /// No return type. /// </remarks> public static readonly SymbolDisplayFormat NameFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> public static readonly SymbolDisplayFormat SignatureFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType); } }
// Licensed to the .NET Foundation under one or more 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.Shared.Extensions { internal static class SymbolDisplayFormats { /// <summary> /// Standard format for displaying to the user. /// </summary> /// <remarks> /// No return type. /// </remarks> public static readonly SymbolDisplayFormat NameFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> public static readonly SymbolDisplayFormat SignatureFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/VisualStudio/Core/Def/EditorConfigSettings/Common/RemoveSinkWhenDisposed.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal class RemoveSinkWhenDisposed : IDisposable { private readonly List<ITableDataSink> _tableSinks; private readonly ITableDataSink _sink; public RemoveSinkWhenDisposed(List<ITableDataSink> tableSinks, ITableDataSink sink) { _tableSinks = tableSinks; _sink = sink; } public void Dispose() { // whoever subscribed is no longer interested in my data. // Remove them from the list of sinks _ = _tableSinks.Remove(_sink); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal class RemoveSinkWhenDisposed : IDisposable { private readonly List<ITableDataSink> _tableSinks; private readonly ITableDataSink _sink; public RemoveSinkWhenDisposed(List<ITableDataSink> tableSinks, ITableDataSink sink) { _tableSinks = tableSinks; _sink = sink; } public void Dispose() { // whoever subscribed is no longer interested in my data. // Remove them from the list of sinks _ = _tableSinks.Remove(_sink); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Errors/XmlParseErrorCode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal enum XmlParseErrorCode { XML_RefUndefinedEntity_1, XML_InvalidCharEntity, XML_InvalidUnicodeChar, XML_InvalidWhitespace, XML_MissingEqualsAttribute, XML_StringLiteralNoStartQuote, XML_StringLiteralNoEndQuote, XML_StringLiteralNonAsciiQuote, XML_LessThanInAttributeValue, XML_IncorrectComment, XML_ElementTypeMatch, XML_DuplicateAttribute, XML_WhitespaceMissing, XML_EndTagNotExpected, XML_CDataEndTagNotAllowed, XML_EndTagExpected, XML_ExpectedIdentifier, XML_ExpectedEndOfTag, // This is the default case for when we find an unexpected token. It // does not correspond to any MSXML error. XML_InvalidToken, XML_ExpectedEndOfXml, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal enum XmlParseErrorCode { XML_RefUndefinedEntity_1, XML_InvalidCharEntity, XML_InvalidUnicodeChar, XML_InvalidWhitespace, XML_MissingEqualsAttribute, XML_StringLiteralNoStartQuote, XML_StringLiteralNoEndQuote, XML_StringLiteralNonAsciiQuote, XML_LessThanInAttributeValue, XML_IncorrectComment, XML_ElementTypeMatch, XML_DuplicateAttribute, XML_WhitespaceMissing, XML_EndTagNotExpected, XML_CDataEndTagNotAllowed, XML_EndTagExpected, XML_ExpectedIdentifier, XML_ExpectedEndOfTag, // This is the default case for when we find an unexpected token. It // does not correspond to any MSXML error. XML_InvalidToken, XML_ExpectedEndOfXml, } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SemanticModelExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SemanticModelExtensions { /// <summary> /// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token. /// </summary> /// <param name="semanticModel">The SemanticModel object to get semantic information /// from.</param> /// <param name="token">The token to get semantic information from. This must be part of the /// syntax tree associated with the binding.</param> /// <param name="cancellationToken">A cancellation token.</param> public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) => semanticModel.GetSymbolInfo(token.Parent!, cancellationToken); public static ISymbol GetRequiredDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken) { return semanticModel.GetDeclaredSymbol(declaration, cancellationToken) ?? throw new InvalidOperationException(); } public static IOperation GetRequiredOperation(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { return semanticModel.GetOperation(node, cancellationToken) ?? throw new InvalidOperationException(); } public static ISymbol GetRequiredEnclosingSymbol(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol(position, cancellationToken) ?? throw new InvalidOperationException(); } public static TSymbol? GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) where TSymbol : class, ISymbol { for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); symbol != null; symbol = symbol.ContainingSymbol) { if (symbol is TSymbol tSymbol) { return tSymbol; } } return null; } public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ?? (ISymbol)semanticModel.Compilation.Assembly; } public static INamedTypeSymbol? GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken); public static INamespaceSymbol? GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken); public static IEnumerable<ISymbol> GetExistingSymbols( this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null) { // Ignore an anonymous type property or tuple field. It's ok if they have a name that // matches the name of the local we're introducing. return semanticModel.GetAllDeclaredSymbols(container, cancellationToken, descendInto) .Where(s => !s.IsAnonymousTypeProperty() && !s.IsTupleField()); } public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel) { if (!semanticModel.IsSpeculativeSemanticModel) { return semanticModel; } Contract.ThrowIfNull(semanticModel.ParentModel); Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel); Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null); return semanticModel.ParentModel; } public static HashSet<ISymbol> GetAllDeclaredSymbols( this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? filter = null) { var symbols = new HashSet<ISymbol>(); if (container != null) { GetAllDeclaredSymbols(semanticModel, container, symbols, cancellationToken, filter); } return symbols; } private static void GetAllDeclaredSymbols( SemanticModel semanticModel, SyntaxNode node, HashSet<ISymbol> symbols, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null) { var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (symbol != null) { symbols.Add(symbol); } foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) { var childNode = child.AsNode()!; if (ShouldDescendInto(childNode, descendInto)) { GetAllDeclaredSymbols(semanticModel, childNode, symbols, cancellationToken, descendInto); } } } static bool ShouldDescendInto(SyntaxNode node, Func<SyntaxNode, bool>? filter) => filter != null ? filter(node) : 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.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SemanticModelExtensions { /// <summary> /// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token. /// </summary> /// <param name="semanticModel">The SemanticModel object to get semantic information /// from.</param> /// <param name="token">The token to get semantic information from. This must be part of the /// syntax tree associated with the binding.</param> /// <param name="cancellationToken">A cancellation token.</param> public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) => semanticModel.GetSymbolInfo(token.Parent!, cancellationToken); public static ISymbol GetRequiredDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken) { return semanticModel.GetDeclaredSymbol(declaration, cancellationToken) ?? throw new InvalidOperationException(); } public static IOperation GetRequiredOperation(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { return semanticModel.GetOperation(node, cancellationToken) ?? throw new InvalidOperationException(); } public static ISymbol GetRequiredEnclosingSymbol(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol(position, cancellationToken) ?? throw new InvalidOperationException(); } public static TSymbol? GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) where TSymbol : class, ISymbol { for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); symbol != null; symbol = symbol.ContainingSymbol) { if (symbol is TSymbol tSymbol) { return tSymbol; } } return null; } public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ?? (ISymbol)semanticModel.Compilation.Assembly; } public static INamedTypeSymbol? GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken); public static INamespaceSymbol? GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken); public static IEnumerable<ISymbol> GetExistingSymbols( this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null) { // Ignore an anonymous type property or tuple field. It's ok if they have a name that // matches the name of the local we're introducing. return semanticModel.GetAllDeclaredSymbols(container, cancellationToken, descendInto) .Where(s => !s.IsAnonymousTypeProperty() && !s.IsTupleField()); } public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel) { if (!semanticModel.IsSpeculativeSemanticModel) { return semanticModel; } Contract.ThrowIfNull(semanticModel.ParentModel); Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel); Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null); return semanticModel.ParentModel; } public static HashSet<ISymbol> GetAllDeclaredSymbols( this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? filter = null) { var symbols = new HashSet<ISymbol>(); if (container != null) { GetAllDeclaredSymbols(semanticModel, container, symbols, cancellationToken, filter); } return symbols; } private static void GetAllDeclaredSymbols( SemanticModel semanticModel, SyntaxNode node, HashSet<ISymbol> symbols, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null) { var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (symbol != null) { symbols.Add(symbol); } foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) { var childNode = child.AsNode()!; if (ShouldDescendInto(childNode, descendInto)) { GetAllDeclaredSymbols(semanticModel, childNode, symbols, cancellationToken, descendInto); } } } static bool ShouldDescendInto(SyntaxNode node, Func<SyntaxNode, bool>? filter) => filter != null ? filter(node) : true; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/WithNullableContextBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class WithNullableContextBinder : Binder { private readonly SyntaxTree _syntaxTree; private readonly int _position; internal WithNullableContextBinder(SyntaxTree syntaxTree, int position, Binder next) : base(next) { Debug.Assert(syntaxTree != null); Debug.Assert(position >= 0); _syntaxTree = syntaxTree; _position = position; } internal override bool AreNullableAnnotationsGloballyEnabled() { return Next.AreNullableAnnotationsEnabled(_syntaxTree, _position); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class WithNullableContextBinder : Binder { private readonly SyntaxTree _syntaxTree; private readonly int _position; internal WithNullableContextBinder(SyntaxTree syntaxTree, int position, Binder next) : base(next) { Debug.Assert(syntaxTree != null); Debug.Assert(position >= 0); _syntaxTree = syntaxTree; _position = position; } internal override bool AreNullableAnnotationsGloballyEnabled() { return Next.AreNullableAnnotationsEnabled(_syntaxTree, _position); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/ParenthesizedExpressionSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class ParenthesizedExpressionSyntaxExtensions { public static bool CanRemoveParentheses( this ParenthesizedExpressionSyntax node, SemanticModel semanticModel, CancellationToken cancellationToken) { if (node.OpenParenToken.IsMissing || node.CloseParenToken.IsMissing) { // int x = (3; return false; } var expression = node.Expression; // The 'direct' expression that contains this parenthesized node. Note: in the case // of code like: ```x is (y)``` there is an intermediary 'no-syntax' 'ConstantPattern' // node between the 'is-pattern' node and the parenthesized expression. So we manually // jump past that as, for all intents and purposes, we want to consider the 'is' expression // as the parent expression of the (y) expression. var parentExpression = node.IsParentKind(SyntaxKind.ConstantPattern) ? node.Parent.Parent as ExpressionSyntax : node.Parent as ExpressionSyntax; // Have to be careful if we would remove parens and cause a + and a + to become a ++. // (same with - as well). var tokenBeforeParen = node.GetFirstToken().GetPreviousToken(); var tokenAfterParen = node.Expression.GetFirstToken(); var previousChar = tokenBeforeParen.Text.LastOrDefault(); var nextChar = tokenAfterParen.Text.FirstOrDefault(); if ((previousChar == '+' && nextChar == '+') || (previousChar == '-' && nextChar == '-')) { return false; } // Simplest cases: // ((x)) -> (x) if (expression.IsKind(SyntaxKind.ParenthesizedExpression) || parentExpression.IsKind(SyntaxKind.ParenthesizedExpression)) { return true; } if (expression is StackAllocArrayCreationExpressionSyntax or ImplicitStackAllocArrayCreationExpressionSyntax) { // var span = (stackalloc byte[8]); // https://github.com/dotnet/roslyn/issues/44629 // The code semantics changes if the parenthesis removed. // With parenthesis: variable span is of type `Span<byte>`. // Without parenthesis: variable span is of type `byte*` which can only be used in unsafe context. return false; } // (throw ...) -> throw ... if (expression.IsKind(SyntaxKind.ThrowExpression)) return true; // (x); -> x; if (node.IsParentKind(SyntaxKind.ExpressionStatement)) { return true; } // => (x) -> => x if (node.IsParentKind(SyntaxKind.ArrowExpressionClause)) { return true; } // checked((x)) -> checked(x) if (node.IsParentKind(SyntaxKind.CheckedExpression) || node.IsParentKind(SyntaxKind.UncheckedExpression)) { return true; } // ((x, y)) -> (x, y) if (expression.IsKind(SyntaxKind.TupleExpression)) { return true; } // int Prop => (x); -> int Prop => x; if (node.Parent is ArrowExpressionClauseSyntax arrowExpressionClause && arrowExpressionClause.Expression == node) { return true; } // Easy statement-level cases: // var y = (x); -> var y = x; // var (y, z) = (x); -> var (y, z) = x; // if ((x)) -> if (x) // return (x); -> return x; // yield return (x); -> yield return x; // throw (x); -> throw x; // switch ((x)) -> switch (x) // while ((x)) -> while (x) // do { } while ((x)) -> do { } while (x) // for(;(x);) -> for(;x;) // foreach (var y in (x)) -> foreach (var y in x) // lock ((x)) -> lock (x) // using ((x)) -> using (x) // catch when ((x)) -> catch when (x) if ((node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax equalsValue) && equalsValue.Value == node) || (node.IsParentKind(SyntaxKind.IfStatement, out IfStatementSyntax ifStatement) && ifStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ReturnStatement, out ReturnStatementSyntax returnStatement) && returnStatement.Expression == node) || (node.IsParentKind(SyntaxKind.YieldReturnStatement, out YieldStatementSyntax yieldStatement) && yieldStatement.Expression == node) || (node.IsParentKind(SyntaxKind.ThrowStatement, out ThrowStatementSyntax throwStatement) && throwStatement.Expression == node) || (node.IsParentKind(SyntaxKind.SwitchStatement, out SwitchStatementSyntax switchStatement) && switchStatement.Expression == node) || (node.IsParentKind(SyntaxKind.WhileStatement, out WhileStatementSyntax whileStatement) && whileStatement.Condition == node) || (node.IsParentKind(SyntaxKind.DoStatement, out DoStatementSyntax doStatement) && doStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ForStatement, out ForStatementSyntax forStatement) && forStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement) && ((CommonForEachStatementSyntax)node.Parent).Expression == node) || (node.IsParentKind(SyntaxKind.LockStatement, out LockStatementSyntax lockStatement) && lockStatement.Expression == node) || (node.IsParentKind(SyntaxKind.UsingStatement, out UsingStatementSyntax usingStatement) && usingStatement.Expression == node) || (node.IsParentKind(SyntaxKind.CatchFilterClause, out CatchFilterClauseSyntax catchFilter) && catchFilter.FilterExpression == node)) { return true; } // Handle expression-level ambiguities if (RemovalMayIntroduceCastAmbiguity(node) || RemovalMayIntroduceCommaListAmbiguity(node) || RemovalMayIntroduceInterpolationAmbiguity(node) || RemovalWouldChangeConstantReferenceToTypeReference(node, expression, semanticModel, cancellationToken)) { return false; } // Cases: // (C)(this) -> (C)this if (node.IsParentKind(SyntaxKind.CastExpression) && expression.IsKind(SyntaxKind.ThisExpression)) { return true; } // Cases: // y((x)) -> y(x) if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument) && argument.Expression == node) { return true; } // Cases: // $"{(x)}" -> $"{x}" if (node.IsParentKind(SyntaxKind.Interpolation)) { return true; } // Cases: // ($"{x}") -> $"{x}" if (expression.IsKind(SyntaxKind.InterpolatedStringExpression)) { return true; } // Cases: // {(x)} -> {x} if (node.Parent is InitializerExpressionSyntax) { // Assignment expressions are not allowed in initializers if (expression.IsAnyAssignExpression()) { return false; } return true; } // Cases: // new {(x)} -> {x} // new { a = (x)} -> { a = x } // new { a = (x = c)} -> { a = x = c } if (node.Parent is AnonymousObjectMemberDeclaratorSyntax anonymousDeclarator) { // Assignment expressions are not allowed unless member is named if (anonymousDeclarator.NameEquals == null && expression.IsAnyAssignExpression()) { return false; } return true; } // Cases: // where (x + 1 > 14) -> where x + 1 > 14 if (node.Parent is QueryClauseSyntax) { return true; } // Cases: // (x) -> x // (x.y) -> x.y if (IsSimpleOrDottedName(expression)) { return true; } // Cases: // ('') -> '' // ("") -> "" // (false) -> false // (true) -> true // (null) -> null // (default) -> default; // (1) -> 1 if (expression.IsAnyLiteralExpression()) { return true; } // (this) -> this if (expression.IsKind(SyntaxKind.ThisExpression)) { return true; } // x ?? (throw ...) -> x ?? throw ... if (expression.IsKind(SyntaxKind.ThrowExpression) && node.IsParentKind(SyntaxKind.CoalesceExpression, out BinaryExpressionSyntax binary) && binary.Right == node) { return true; } // case (x): -> case x: if (node.IsParentKind(SyntaxKind.CaseSwitchLabel)) { return true; } // case (x) when y: -> case x when y: if (node.IsParentKind(SyntaxKind.ConstantPattern) && node.Parent.IsParentKind(SyntaxKind.CasePatternSwitchLabel)) { return true; } // case x when (y): -> case x when y: if (node.IsParentKind(SyntaxKind.WhenClause)) { return true; } // #if (x) -> #if x if (node.Parent is DirectiveTriviaSyntax) { return true; } // Switch expression arm // x => (y) if (node.Parent is SwitchExpressionArmSyntax arm && arm.Expression == node) { return true; } // If we have: (X)(++x) or (X)(--x), we don't want to remove the parens. doing so can // make the ++/-- now associate with the previous part of the cast expression. if (parentExpression.IsKind(SyntaxKind.CastExpression)) { if (expression.IsKind(SyntaxKind.PreIncrementExpression) || expression.IsKind(SyntaxKind.PreDecrementExpression)) { return false; } } // (condition ? ref a : ref b ) = SomeValue, parenthesis can't be removed for when conditional expression appears at left // This syntax is only allowed since C# 7.2 if (expression.IsKind(SyntaxKind.ConditionalExpression) && node.IsLeftSideOfAnyAssignExpression()) { return false; } // Don't change (x?.Count)... to x?.Count... // // It very much changes the semantics to have code that always executed (outside the // parenthesized expression) now only conditionally run depending on if 'x' is null or // not. if (expression.IsKind(SyntaxKind.ConditionalAccessExpression)) { return false; } // Operator precedence cases: // - If the parent is not an expression, do not remove parentheses // - Otherwise, parentheses may be removed if doing so does not change operator associations. return parentExpression != null && !RemovalChangesAssociation(node, parentExpression, semanticModel); } private static bool RemovalWouldChangeConstantReferenceToTypeReference( ParenthesizedExpressionSyntax node, ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // With cases like: `if (x is (Y))` then we cannot remove the parens if it would make Y now bind to a type // instead of a constant. if (node.Parent is not ConstantPatternSyntax { Parent: IsPatternExpressionSyntax }) return false; var exprSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (exprSymbol is not IFieldSymbol { IsConst: true } field) return false; // See if interpreting the same expression as a type in this location binds. var potentialType = semanticModel.GetSpeculativeTypeInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; return potentialType is not (null or IErrorTypeSymbol); } private static readonly ObjectPool<Stack<SyntaxNode>> s_nodeStackPool = SharedPools.Default<Stack<SyntaxNode>>(); private static bool RemovalMayIntroduceInterpolationAmbiguity(ParenthesizedExpressionSyntax node) { // First, find the parenting interpolation. If we find a parenthesize expression first, // we can bail out early. InterpolationSyntax interpolation = null; foreach (var ancestor in node.Parent.AncestorsAndSelf()) { if (ancestor.IsKind(SyntaxKind.ParenthesizedExpression)) { return false; } if (ancestor.IsKind(SyntaxKind.Interpolation, out interpolation)) { break; } } if (interpolation == null) { return false; } // In order determine whether removing this parenthesized expression will introduce a // parsing ambiguity, we must dig into the child tokens and nodes to determine whether // they include any : or :: tokens. If they do, we can't remove the parentheses because // the parser would assume that the first : would begin the format clause of the interpolation. var stack = s_nodeStackPool.AllocateAndClear(); try { stack.Push(node.Expression); while (stack.Count > 0) { var expression = stack.Pop(); foreach (var nodeOrToken in expression.ChildNodesAndTokens()) { // Note: There's no need drill into other parenthesized expressions, since any colons in them would be unambiguous. if (nodeOrToken.IsNode && !nodeOrToken.IsKind(SyntaxKind.ParenthesizedExpression)) { stack.Push(nodeOrToken.AsNode()); } else if (nodeOrToken.IsToken) { if (nodeOrToken.IsKind(SyntaxKind.ColonToken) || nodeOrToken.IsKind(SyntaxKind.ColonColonToken)) { return true; } } } } } finally { s_nodeStackPool.ClearAndFree(stack); } return false; } private static bool RemovalChangesAssociation( ParenthesizedExpressionSyntax node, ExpressionSyntax parentExpression, SemanticModel semanticModel) { var expression = node.Expression; var precedence = expression.GetOperatorPrecedence(); var parentPrecedence = parentExpression.GetOperatorPrecedence(); if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None) { // Be conservative if the expression or its parent has no precedence. return true; } if (precedence > parentPrecedence) { // Association never changes if the expression's precedence is higher than its parent. return false; } else if (precedence < parentPrecedence) { // Association always changes if the expression's precedence is lower that its parent. return true; } else if (precedence == parentPrecedence) { // If the expression's precedence is the same as its parent, and both are binary expressions, // check for associativity and commutability. if (expression is not (BinaryExpressionSyntax or AssignmentExpressionSyntax)) { // If the expression is not a binary expression, association never changes. return false; } if (parentExpression is BinaryExpressionSyntax parentBinaryExpression) { // If both the expression and its parent are binary expressions and their kinds // are the same, and the parenthesized expression is on hte right and the // operation is associative, it can sometimes be safe to remove these parens. // // i.e. if you have "a && (b && c)" it can be converted to "a && b && c" // as that new interpretation "(a && b) && c" operates the exact same way at // runtime. // // Specifically: // 1) the operands are still executed in the same order: a, b, then c. // So even if they have side effects, it will not matter. // 2) the same shortcircuiting happens. // 3) for logical operators the result will always be the same (there are // additional conditions that are checked for non-logical operators). if (IsAssociative(parentBinaryExpression.Kind()) && node.Expression.Kind() == parentBinaryExpression.Kind() && parentBinaryExpression.Right == node) { return !node.IsSafeToChangeAssociativity( node.Expression, parentBinaryExpression.Left, parentBinaryExpression.Right, semanticModel); } // Null-coalescing is right associative; removing parens from the LHS changes the association. if (parentExpression.IsKind(SyntaxKind.CoalesceExpression)) { return parentBinaryExpression.Left == node; } // All other binary operators are left associative; removing parens from the RHS changes the association. return parentBinaryExpression.Right == node; } if (parentExpression is AssignmentExpressionSyntax parentAssignmentExpression) { // Assignment expressions are right associative; removing parens from the LHS changes the association. return parentAssignmentExpression.Left == node; } // If the parent is not a binary expression, association never changes. return false; } throw ExceptionUtilities.Unreachable; } private static bool IsAssociative(SyntaxKind kind) { switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.LogicalAndExpression: return true; } return false; } private static bool RemovalMayIntroduceCastAmbiguity(ParenthesizedExpressionSyntax node) { // Be careful not to break the special case around (x)(-y) // as defined in section 7.7.6 of the C# language specification. // // cases we can't remove the parens for are: // // (x)(+y) // (x)(-y) // (x)(&y) // unsafe code // (x)(*y) // unsafe code // // Note: we can remove the parens if the (x) part is unambiguously a type. // i.e. if it something like: // // (int)(...) // (x[])(...) // (X*)(...) // (X?)(...) // (global::X)(...) if (node.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression)) { if (castExpression.Type.IsKind( SyntaxKind.PredefinedType, SyntaxKind.ArrayType, SyntaxKind.PointerType, SyntaxKind.NullableType)) { return false; } if (castExpression.Type is NameSyntax name && StartsWithAlias(name)) { return false; } var expression = node.Expression; if (expression.IsKind( SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression, SyntaxKind.PointerIndirectionExpression, SyntaxKind.AddressOfExpression)) { return true; } } return false; } private static bool StartsWithAlias(NameSyntax name) { if (name.IsKind(SyntaxKind.AliasQualifiedName)) { return true; } if (name is QualifiedNameSyntax qualifiedName) { return StartsWithAlias(qualifiedName.Left); } return false; } private static bool RemovalMayIntroduceCommaListAmbiguity(ParenthesizedExpressionSyntax node) { if (IsSimpleOrDottedName(node.Expression)) { // We can't remove parentheses from an identifier name in the following cases: // F((x) < x, x > (1 + 2)) // F(x < (x), x > (1 + 2)) // F(x < x, (x) > (1 + 2)) // {(x) < x, x > (1 + 2)} // {x < (x), x > (1 + 2)} // {x < x, (x) > (1 + 2)} if (node.Parent is BinaryExpressionSyntax binaryExpression && binaryExpression.IsKind(SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression) && (binaryExpression.IsParentKind(SyntaxKind.Argument) || binaryExpression.Parent is InitializerExpressionSyntax)) { if (binaryExpression.IsKind(SyntaxKind.LessThanExpression)) { if ((binaryExpression.Left == node && IsSimpleOrDottedName(binaryExpression.Right)) || (binaryExpression.Right == node && IsSimpleOrDottedName(binaryExpression.Left))) { if (IsNextExpressionPotentiallyAmbiguous(binaryExpression)) { return true; } } return false; } else if (binaryExpression.IsKind(SyntaxKind.GreaterThanExpression)) { if (binaryExpression.Left == node && binaryExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.CastExpression)) { if (IsPreviousExpressionPotentiallyAmbiguous(binaryExpression)) { return true; } } return false; } } } else if (node.Expression.IsKind(SyntaxKind.LessThanExpression)) { // We can't remove parentheses from a less-than expression in the following cases: // F((x < x), x > (1 + 2)) // {(x < x), x > (1 + 2)} return IsNextExpressionPotentiallyAmbiguous(node); } else if (node.Expression.IsKind(SyntaxKind.GreaterThanExpression)) { // We can't remove parentheses from a greater-than expression in the following cases: // F(x < x, (x > (1 + 2))) // {x < x, (x > (1 + 2))} return IsPreviousExpressionPotentiallyAmbiguous(node); } return false; } private static bool IsPreviousExpressionPotentiallyAmbiguous(ExpressionSyntax node) { ExpressionSyntax previousExpression = null; if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument)) { if (argument.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex > 0) { previousExpression = argumentList.Arguments[argumentIndex - 1].Expression; } } } else if (node.Parent is InitializerExpressionSyntax initializer) { var expressionIndex = initializer.Expressions.IndexOf(node); if (expressionIndex > 0) { previousExpression = initializer.Expressions[expressionIndex - 1]; } } if (previousExpression == null || !previousExpression.IsKind(SyntaxKind.LessThanExpression, out BinaryExpressionSyntax lessThanExpression)) { return false; } return (IsSimpleOrDottedName(lessThanExpression.Left) || lessThanExpression.Left.IsKind(SyntaxKind.CastExpression)) && IsSimpleOrDottedName(lessThanExpression.Right); } private static bool IsNextExpressionPotentiallyAmbiguous(ExpressionSyntax node) { ExpressionSyntax nextExpression = null; if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument)) { if (argument.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex >= 0 && argumentIndex < argumentList.Arguments.Count - 1) { nextExpression = argumentList.Arguments[argumentIndex + 1].Expression; } } } else if (node.Parent is InitializerExpressionSyntax initializer) { var expressionIndex = initializer.Expressions.IndexOf(node); if (expressionIndex >= 0 && expressionIndex < initializer.Expressions.Count - 1) { nextExpression = initializer.Expressions[expressionIndex + 1]; } } if (nextExpression == null || !nextExpression.IsKind(SyntaxKind.GreaterThanExpression, out BinaryExpressionSyntax greaterThanExpression)) { return false; } return IsSimpleOrDottedName(greaterThanExpression.Left) && (greaterThanExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression) || greaterThanExpression.Right.IsKind(SyntaxKind.CastExpression)); } private static bool IsSimpleOrDottedName(ExpressionSyntax expression) => expression.Kind() is SyntaxKind.IdentifierName or SyntaxKind.QualifiedName or SyntaxKind.SimpleMemberAccessExpression; public static bool CanRemoveParentheses(this ParenthesizedPatternSyntax node) { if (node.OpenParenToken.IsMissing || node.CloseParenToken.IsMissing) { // int x = (3; return false; } var pattern = node.Pattern; // We wrap a parenthesized pattern and we're parenthesized. We can remove our parens. if (pattern is ParenthesizedPatternSyntax) return true; // We're parenthesized discard pattern. We cannot remove parens. // x is (_) if (pattern is DiscardPatternSyntax && node.Parent is IsPatternExpressionSyntax) return false; // (not ...) -> not ... // // this is safe because unary patterns have the highest precedence, so even if you had: // (not ...) or (not ...) // // you can safely convert to `not ... or not ...` var patternPrecedence = pattern.GetOperatorPrecedence(); if (patternPrecedence is OperatorPrecedence.Primary or OperatorPrecedence.Unary) return true; // We're parenthesized and are inside a parenthesized pattern. We can remove our parens. // ((x)) -> (x) if (node.Parent is ParenthesizedPatternSyntax) return true; // x is (...) -> x is ... if (node.Parent is IsPatternExpressionSyntax) return true; // (x or y) => ... -> x or y => ... if (node.Parent is SwitchExpressionArmSyntax) return true; // X: (y or z) -> X: y or z if (node.Parent is SubpatternSyntax) return true; // case (x or y): -> case x or y: if (node.Parent is CasePatternSwitchLabelSyntax) return true; // Operator precedence cases: // - If the parent is not an expression, do not remove parentheses // - Otherwise, parentheses may be removed if doing so does not change operator associations. return node.Parent is PatternSyntax patternParent && !RemovalChangesAssociation(node, patternParent); } private static bool RemovalChangesAssociation( ParenthesizedPatternSyntax node, PatternSyntax parentPattern) { var pattern = node.Pattern; var precedence = pattern.GetOperatorPrecedence(); var parentPrecedence = parentPattern.GetOperatorPrecedence(); if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None) { // Be conservative if the expression or its parent has no precedence. return true; } // Association always changes if the expression's precedence is lower that its parent. return precedence < parentPrecedence; } public static OperatorPrecedence GetOperatorPrecedence(this PatternSyntax pattern) { switch (pattern) { case ConstantPatternSyntax _: case DiscardPatternSyntax _: case DeclarationPatternSyntax _: case RecursivePatternSyntax _: case TypePatternSyntax _: case VarPatternSyntax _: return OperatorPrecedence.Primary; case UnaryPatternSyntax _: case RelationalPatternSyntax _: return OperatorPrecedence.Unary; case BinaryPatternSyntax binaryPattern: if (binaryPattern.IsKind(SyntaxKind.AndPattern)) return OperatorPrecedence.ConditionalAnd; if (binaryPattern.IsKind(SyntaxKind.OrPattern)) return OperatorPrecedence.ConditionalOr; break; } Debug.Fail("Unhandled pattern type"); return OperatorPrecedence.None; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class ParenthesizedExpressionSyntaxExtensions { public static bool CanRemoveParentheses( this ParenthesizedExpressionSyntax node, SemanticModel semanticModel, CancellationToken cancellationToken) { if (node.OpenParenToken.IsMissing || node.CloseParenToken.IsMissing) { // int x = (3; return false; } var expression = node.Expression; // The 'direct' expression that contains this parenthesized node. Note: in the case // of code like: ```x is (y)``` there is an intermediary 'no-syntax' 'ConstantPattern' // node between the 'is-pattern' node and the parenthesized expression. So we manually // jump past that as, for all intents and purposes, we want to consider the 'is' expression // as the parent expression of the (y) expression. var parentExpression = node.IsParentKind(SyntaxKind.ConstantPattern) ? node.Parent.Parent as ExpressionSyntax : node.Parent as ExpressionSyntax; // Have to be careful if we would remove parens and cause a + and a + to become a ++. // (same with - as well). var tokenBeforeParen = node.GetFirstToken().GetPreviousToken(); var tokenAfterParen = node.Expression.GetFirstToken(); var previousChar = tokenBeforeParen.Text.LastOrDefault(); var nextChar = tokenAfterParen.Text.FirstOrDefault(); if ((previousChar == '+' && nextChar == '+') || (previousChar == '-' && nextChar == '-')) { return false; } // Simplest cases: // ((x)) -> (x) if (expression.IsKind(SyntaxKind.ParenthesizedExpression) || parentExpression.IsKind(SyntaxKind.ParenthesizedExpression)) { return true; } if (expression is StackAllocArrayCreationExpressionSyntax or ImplicitStackAllocArrayCreationExpressionSyntax) { // var span = (stackalloc byte[8]); // https://github.com/dotnet/roslyn/issues/44629 // The code semantics changes if the parenthesis removed. // With parenthesis: variable span is of type `Span<byte>`. // Without parenthesis: variable span is of type `byte*` which can only be used in unsafe context. return false; } // (throw ...) -> throw ... if (expression.IsKind(SyntaxKind.ThrowExpression)) return true; // (x); -> x; if (node.IsParentKind(SyntaxKind.ExpressionStatement)) { return true; } // => (x) -> => x if (node.IsParentKind(SyntaxKind.ArrowExpressionClause)) { return true; } // checked((x)) -> checked(x) if (node.IsParentKind(SyntaxKind.CheckedExpression) || node.IsParentKind(SyntaxKind.UncheckedExpression)) { return true; } // ((x, y)) -> (x, y) if (expression.IsKind(SyntaxKind.TupleExpression)) { return true; } // int Prop => (x); -> int Prop => x; if (node.Parent is ArrowExpressionClauseSyntax arrowExpressionClause && arrowExpressionClause.Expression == node) { return true; } // Easy statement-level cases: // var y = (x); -> var y = x; // var (y, z) = (x); -> var (y, z) = x; // if ((x)) -> if (x) // return (x); -> return x; // yield return (x); -> yield return x; // throw (x); -> throw x; // switch ((x)) -> switch (x) // while ((x)) -> while (x) // do { } while ((x)) -> do { } while (x) // for(;(x);) -> for(;x;) // foreach (var y in (x)) -> foreach (var y in x) // lock ((x)) -> lock (x) // using ((x)) -> using (x) // catch when ((x)) -> catch when (x) if ((node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax equalsValue) && equalsValue.Value == node) || (node.IsParentKind(SyntaxKind.IfStatement, out IfStatementSyntax ifStatement) && ifStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ReturnStatement, out ReturnStatementSyntax returnStatement) && returnStatement.Expression == node) || (node.IsParentKind(SyntaxKind.YieldReturnStatement, out YieldStatementSyntax yieldStatement) && yieldStatement.Expression == node) || (node.IsParentKind(SyntaxKind.ThrowStatement, out ThrowStatementSyntax throwStatement) && throwStatement.Expression == node) || (node.IsParentKind(SyntaxKind.SwitchStatement, out SwitchStatementSyntax switchStatement) && switchStatement.Expression == node) || (node.IsParentKind(SyntaxKind.WhileStatement, out WhileStatementSyntax whileStatement) && whileStatement.Condition == node) || (node.IsParentKind(SyntaxKind.DoStatement, out DoStatementSyntax doStatement) && doStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ForStatement, out ForStatementSyntax forStatement) && forStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement) && ((CommonForEachStatementSyntax)node.Parent).Expression == node) || (node.IsParentKind(SyntaxKind.LockStatement, out LockStatementSyntax lockStatement) && lockStatement.Expression == node) || (node.IsParentKind(SyntaxKind.UsingStatement, out UsingStatementSyntax usingStatement) && usingStatement.Expression == node) || (node.IsParentKind(SyntaxKind.CatchFilterClause, out CatchFilterClauseSyntax catchFilter) && catchFilter.FilterExpression == node)) { return true; } // Handle expression-level ambiguities if (RemovalMayIntroduceCastAmbiguity(node) || RemovalMayIntroduceCommaListAmbiguity(node) || RemovalMayIntroduceInterpolationAmbiguity(node) || RemovalWouldChangeConstantReferenceToTypeReference(node, expression, semanticModel, cancellationToken)) { return false; } // Cases: // (C)(this) -> (C)this if (node.IsParentKind(SyntaxKind.CastExpression) && expression.IsKind(SyntaxKind.ThisExpression)) { return true; } // Cases: // y((x)) -> y(x) if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument) && argument.Expression == node) { return true; } // Cases: // $"{(x)}" -> $"{x}" if (node.IsParentKind(SyntaxKind.Interpolation)) { return true; } // Cases: // ($"{x}") -> $"{x}" if (expression.IsKind(SyntaxKind.InterpolatedStringExpression)) { return true; } // Cases: // {(x)} -> {x} if (node.Parent is InitializerExpressionSyntax) { // Assignment expressions are not allowed in initializers if (expression.IsAnyAssignExpression()) { return false; } return true; } // Cases: // new {(x)} -> {x} // new { a = (x)} -> { a = x } // new { a = (x = c)} -> { a = x = c } if (node.Parent is AnonymousObjectMemberDeclaratorSyntax anonymousDeclarator) { // Assignment expressions are not allowed unless member is named if (anonymousDeclarator.NameEquals == null && expression.IsAnyAssignExpression()) { return false; } return true; } // Cases: // where (x + 1 > 14) -> where x + 1 > 14 if (node.Parent is QueryClauseSyntax) { return true; } // Cases: // (x) -> x // (x.y) -> x.y if (IsSimpleOrDottedName(expression)) { return true; } // Cases: // ('') -> '' // ("") -> "" // (false) -> false // (true) -> true // (null) -> null // (default) -> default; // (1) -> 1 if (expression.IsAnyLiteralExpression()) { return true; } // (this) -> this if (expression.IsKind(SyntaxKind.ThisExpression)) { return true; } // x ?? (throw ...) -> x ?? throw ... if (expression.IsKind(SyntaxKind.ThrowExpression) && node.IsParentKind(SyntaxKind.CoalesceExpression, out BinaryExpressionSyntax binary) && binary.Right == node) { return true; } // case (x): -> case x: if (node.IsParentKind(SyntaxKind.CaseSwitchLabel)) { return true; } // case (x) when y: -> case x when y: if (node.IsParentKind(SyntaxKind.ConstantPattern) && node.Parent.IsParentKind(SyntaxKind.CasePatternSwitchLabel)) { return true; } // case x when (y): -> case x when y: if (node.IsParentKind(SyntaxKind.WhenClause)) { return true; } // #if (x) -> #if x if (node.Parent is DirectiveTriviaSyntax) { return true; } // Switch expression arm // x => (y) if (node.Parent is SwitchExpressionArmSyntax arm && arm.Expression == node) { return true; } // If we have: (X)(++x) or (X)(--x), we don't want to remove the parens. doing so can // make the ++/-- now associate with the previous part of the cast expression. if (parentExpression.IsKind(SyntaxKind.CastExpression)) { if (expression.IsKind(SyntaxKind.PreIncrementExpression) || expression.IsKind(SyntaxKind.PreDecrementExpression)) { return false; } } // (condition ? ref a : ref b ) = SomeValue, parenthesis can't be removed for when conditional expression appears at left // This syntax is only allowed since C# 7.2 if (expression.IsKind(SyntaxKind.ConditionalExpression) && node.IsLeftSideOfAnyAssignExpression()) { return false; } // Don't change (x?.Count)... to x?.Count... // // It very much changes the semantics to have code that always executed (outside the // parenthesized expression) now only conditionally run depending on if 'x' is null or // not. if (expression.IsKind(SyntaxKind.ConditionalAccessExpression)) { return false; } // Operator precedence cases: // - If the parent is not an expression, do not remove parentheses // - Otherwise, parentheses may be removed if doing so does not change operator associations. return parentExpression != null && !RemovalChangesAssociation(node, parentExpression, semanticModel); } private static bool RemovalWouldChangeConstantReferenceToTypeReference( ParenthesizedExpressionSyntax node, ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // With cases like: `if (x is (Y))` then we cannot remove the parens if it would make Y now bind to a type // instead of a constant. if (node.Parent is not ConstantPatternSyntax { Parent: IsPatternExpressionSyntax }) return false; var exprSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (exprSymbol is not IFieldSymbol { IsConst: true } field) return false; // See if interpreting the same expression as a type in this location binds. var potentialType = semanticModel.GetSpeculativeTypeInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; return potentialType is not (null or IErrorTypeSymbol); } private static readonly ObjectPool<Stack<SyntaxNode>> s_nodeStackPool = SharedPools.Default<Stack<SyntaxNode>>(); private static bool RemovalMayIntroduceInterpolationAmbiguity(ParenthesizedExpressionSyntax node) { // First, find the parenting interpolation. If we find a parenthesize expression first, // we can bail out early. InterpolationSyntax interpolation = null; foreach (var ancestor in node.Parent.AncestorsAndSelf()) { if (ancestor.IsKind(SyntaxKind.ParenthesizedExpression)) { return false; } if (ancestor.IsKind(SyntaxKind.Interpolation, out interpolation)) { break; } } if (interpolation == null) { return false; } // In order determine whether removing this parenthesized expression will introduce a // parsing ambiguity, we must dig into the child tokens and nodes to determine whether // they include any : or :: tokens. If they do, we can't remove the parentheses because // the parser would assume that the first : would begin the format clause of the interpolation. var stack = s_nodeStackPool.AllocateAndClear(); try { stack.Push(node.Expression); while (stack.Count > 0) { var expression = stack.Pop(); foreach (var nodeOrToken in expression.ChildNodesAndTokens()) { // Note: There's no need drill into other parenthesized expressions, since any colons in them would be unambiguous. if (nodeOrToken.IsNode && !nodeOrToken.IsKind(SyntaxKind.ParenthesizedExpression)) { stack.Push(nodeOrToken.AsNode()); } else if (nodeOrToken.IsToken) { if (nodeOrToken.IsKind(SyntaxKind.ColonToken) || nodeOrToken.IsKind(SyntaxKind.ColonColonToken)) { return true; } } } } } finally { s_nodeStackPool.ClearAndFree(stack); } return false; } private static bool RemovalChangesAssociation( ParenthesizedExpressionSyntax node, ExpressionSyntax parentExpression, SemanticModel semanticModel) { var expression = node.Expression; var precedence = expression.GetOperatorPrecedence(); var parentPrecedence = parentExpression.GetOperatorPrecedence(); if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None) { // Be conservative if the expression or its parent has no precedence. return true; } if (precedence > parentPrecedence) { // Association never changes if the expression's precedence is higher than its parent. return false; } else if (precedence < parentPrecedence) { // Association always changes if the expression's precedence is lower that its parent. return true; } else if (precedence == parentPrecedence) { // If the expression's precedence is the same as its parent, and both are binary expressions, // check for associativity and commutability. if (expression is not (BinaryExpressionSyntax or AssignmentExpressionSyntax)) { // If the expression is not a binary expression, association never changes. return false; } if (parentExpression is BinaryExpressionSyntax parentBinaryExpression) { // If both the expression and its parent are binary expressions and their kinds // are the same, and the parenthesized expression is on hte right and the // operation is associative, it can sometimes be safe to remove these parens. // // i.e. if you have "a && (b && c)" it can be converted to "a && b && c" // as that new interpretation "(a && b) && c" operates the exact same way at // runtime. // // Specifically: // 1) the operands are still executed in the same order: a, b, then c. // So even if they have side effects, it will not matter. // 2) the same shortcircuiting happens. // 3) for logical operators the result will always be the same (there are // additional conditions that are checked for non-logical operators). if (IsAssociative(parentBinaryExpression.Kind()) && node.Expression.Kind() == parentBinaryExpression.Kind() && parentBinaryExpression.Right == node) { return !node.IsSafeToChangeAssociativity( node.Expression, parentBinaryExpression.Left, parentBinaryExpression.Right, semanticModel); } // Null-coalescing is right associative; removing parens from the LHS changes the association. if (parentExpression.IsKind(SyntaxKind.CoalesceExpression)) { return parentBinaryExpression.Left == node; } // All other binary operators are left associative; removing parens from the RHS changes the association. return parentBinaryExpression.Right == node; } if (parentExpression is AssignmentExpressionSyntax parentAssignmentExpression) { // Assignment expressions are right associative; removing parens from the LHS changes the association. return parentAssignmentExpression.Left == node; } // If the parent is not a binary expression, association never changes. return false; } throw ExceptionUtilities.Unreachable; } private static bool IsAssociative(SyntaxKind kind) { switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.LogicalAndExpression: return true; } return false; } private static bool RemovalMayIntroduceCastAmbiguity(ParenthesizedExpressionSyntax node) { // Be careful not to break the special case around (x)(-y) // as defined in section 7.7.6 of the C# language specification. // // cases we can't remove the parens for are: // // (x)(+y) // (x)(-y) // (x)(&y) // unsafe code // (x)(*y) // unsafe code // // Note: we can remove the parens if the (x) part is unambiguously a type. // i.e. if it something like: // // (int)(...) // (x[])(...) // (X*)(...) // (X?)(...) // (global::X)(...) if (node.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression)) { if (castExpression.Type.IsKind( SyntaxKind.PredefinedType, SyntaxKind.ArrayType, SyntaxKind.PointerType, SyntaxKind.NullableType)) { return false; } if (castExpression.Type is NameSyntax name && StartsWithAlias(name)) { return false; } var expression = node.Expression; if (expression.IsKind( SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression, SyntaxKind.PointerIndirectionExpression, SyntaxKind.AddressOfExpression)) { return true; } } return false; } private static bool StartsWithAlias(NameSyntax name) { if (name.IsKind(SyntaxKind.AliasQualifiedName)) { return true; } if (name is QualifiedNameSyntax qualifiedName) { return StartsWithAlias(qualifiedName.Left); } return false; } private static bool RemovalMayIntroduceCommaListAmbiguity(ParenthesizedExpressionSyntax node) { if (IsSimpleOrDottedName(node.Expression)) { // We can't remove parentheses from an identifier name in the following cases: // F((x) < x, x > (1 + 2)) // F(x < (x), x > (1 + 2)) // F(x < x, (x) > (1 + 2)) // {(x) < x, x > (1 + 2)} // {x < (x), x > (1 + 2)} // {x < x, (x) > (1 + 2)} if (node.Parent is BinaryExpressionSyntax binaryExpression && binaryExpression.IsKind(SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression) && (binaryExpression.IsParentKind(SyntaxKind.Argument) || binaryExpression.Parent is InitializerExpressionSyntax)) { if (binaryExpression.IsKind(SyntaxKind.LessThanExpression)) { if ((binaryExpression.Left == node && IsSimpleOrDottedName(binaryExpression.Right)) || (binaryExpression.Right == node && IsSimpleOrDottedName(binaryExpression.Left))) { if (IsNextExpressionPotentiallyAmbiguous(binaryExpression)) { return true; } } return false; } else if (binaryExpression.IsKind(SyntaxKind.GreaterThanExpression)) { if (binaryExpression.Left == node && binaryExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.CastExpression)) { if (IsPreviousExpressionPotentiallyAmbiguous(binaryExpression)) { return true; } } return false; } } } else if (node.Expression.IsKind(SyntaxKind.LessThanExpression)) { // We can't remove parentheses from a less-than expression in the following cases: // F((x < x), x > (1 + 2)) // {(x < x), x > (1 + 2)} return IsNextExpressionPotentiallyAmbiguous(node); } else if (node.Expression.IsKind(SyntaxKind.GreaterThanExpression)) { // We can't remove parentheses from a greater-than expression in the following cases: // F(x < x, (x > (1 + 2))) // {x < x, (x > (1 + 2))} return IsPreviousExpressionPotentiallyAmbiguous(node); } return false; } private static bool IsPreviousExpressionPotentiallyAmbiguous(ExpressionSyntax node) { ExpressionSyntax previousExpression = null; if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument)) { if (argument.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex > 0) { previousExpression = argumentList.Arguments[argumentIndex - 1].Expression; } } } else if (node.Parent is InitializerExpressionSyntax initializer) { var expressionIndex = initializer.Expressions.IndexOf(node); if (expressionIndex > 0) { previousExpression = initializer.Expressions[expressionIndex - 1]; } } if (previousExpression == null || !previousExpression.IsKind(SyntaxKind.LessThanExpression, out BinaryExpressionSyntax lessThanExpression)) { return false; } return (IsSimpleOrDottedName(lessThanExpression.Left) || lessThanExpression.Left.IsKind(SyntaxKind.CastExpression)) && IsSimpleOrDottedName(lessThanExpression.Right); } private static bool IsNextExpressionPotentiallyAmbiguous(ExpressionSyntax node) { ExpressionSyntax nextExpression = null; if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument)) { if (argument.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex >= 0 && argumentIndex < argumentList.Arguments.Count - 1) { nextExpression = argumentList.Arguments[argumentIndex + 1].Expression; } } } else if (node.Parent is InitializerExpressionSyntax initializer) { var expressionIndex = initializer.Expressions.IndexOf(node); if (expressionIndex >= 0 && expressionIndex < initializer.Expressions.Count - 1) { nextExpression = initializer.Expressions[expressionIndex + 1]; } } if (nextExpression == null || !nextExpression.IsKind(SyntaxKind.GreaterThanExpression, out BinaryExpressionSyntax greaterThanExpression)) { return false; } return IsSimpleOrDottedName(greaterThanExpression.Left) && (greaterThanExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression) || greaterThanExpression.Right.IsKind(SyntaxKind.CastExpression)); } private static bool IsSimpleOrDottedName(ExpressionSyntax expression) => expression.Kind() is SyntaxKind.IdentifierName or SyntaxKind.QualifiedName or SyntaxKind.SimpleMemberAccessExpression; public static bool CanRemoveParentheses(this ParenthesizedPatternSyntax node) { if (node.OpenParenToken.IsMissing || node.CloseParenToken.IsMissing) { // int x = (3; return false; } var pattern = node.Pattern; // We wrap a parenthesized pattern and we're parenthesized. We can remove our parens. if (pattern is ParenthesizedPatternSyntax) return true; // We're parenthesized discard pattern. We cannot remove parens. // x is (_) if (pattern is DiscardPatternSyntax && node.Parent is IsPatternExpressionSyntax) return false; // (not ...) -> not ... // // this is safe because unary patterns have the highest precedence, so even if you had: // (not ...) or (not ...) // // you can safely convert to `not ... or not ...` var patternPrecedence = pattern.GetOperatorPrecedence(); if (patternPrecedence is OperatorPrecedence.Primary or OperatorPrecedence.Unary) return true; // We're parenthesized and are inside a parenthesized pattern. We can remove our parens. // ((x)) -> (x) if (node.Parent is ParenthesizedPatternSyntax) return true; // x is (...) -> x is ... if (node.Parent is IsPatternExpressionSyntax) return true; // (x or y) => ... -> x or y => ... if (node.Parent is SwitchExpressionArmSyntax) return true; // X: (y or z) -> X: y or z if (node.Parent is SubpatternSyntax) return true; // case (x or y): -> case x or y: if (node.Parent is CasePatternSwitchLabelSyntax) return true; // Operator precedence cases: // - If the parent is not an expression, do not remove parentheses // - Otherwise, parentheses may be removed if doing so does not change operator associations. return node.Parent is PatternSyntax patternParent && !RemovalChangesAssociation(node, patternParent); } private static bool RemovalChangesAssociation( ParenthesizedPatternSyntax node, PatternSyntax parentPattern) { var pattern = node.Pattern; var precedence = pattern.GetOperatorPrecedence(); var parentPrecedence = parentPattern.GetOperatorPrecedence(); if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None) { // Be conservative if the expression or its parent has no precedence. return true; } // Association always changes if the expression's precedence is lower that its parent. return precedence < parentPrecedence; } public static OperatorPrecedence GetOperatorPrecedence(this PatternSyntax pattern) { switch (pattern) { case ConstantPatternSyntax _: case DiscardPatternSyntax _: case DeclarationPatternSyntax _: case RecursivePatternSyntax _: case TypePatternSyntax _: case VarPatternSyntax _: return OperatorPrecedence.Primary; case UnaryPatternSyntax _: case RelationalPatternSyntax _: return OperatorPrecedence.Unary; case BinaryPatternSyntax binaryPattern: if (binaryPattern.IsKind(SyntaxKind.AndPattern)) return OperatorPrecedence.ConditionalAnd; if (binaryPattern.IsKind(SyntaxKind.OrPattern)) return OperatorPrecedence.ConditionalOr; break; } Debug.Fail("Unhandled pattern type"); return OperatorPrecedence.None; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/VisualStudio/CSharp/Impl/ObjectBrowser/DescriptionBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { internal class DescriptionBuilder : AbstractDescriptionBuilder { public DescriptionBuilder( IVsObjectBrowserDescription3 description, ObjectBrowserLibraryManager libraryManager, ObjectListItem listItem, Project project) : base(description, libraryManager, listItem, project) { } protected override void BuildNamespaceDeclaration(INamespaceSymbol namespaceSymbol, _VSOBJDESCOPTIONS options) { AddText("namespace "); AddName(namespaceSymbol.ToDisplayString()); } protected override void BuildDelegateDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options) { Debug.Assert(typeSymbol.TypeKind == TypeKind.Delegate); BuildTypeModifiers(typeSymbol); AddText("delegate "); var delegateInvokeMethod = typeSymbol.DelegateInvokeMethod; AddTypeLink(delegateInvokeMethod.ReturnType, LinkFlags.None); AddText(" "); var typeQualificationStyle = (options & _VSOBJDESCOPTIONS.ODO_USEFULLNAME) != 0 ? SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces : SymbolDisplayTypeQualificationStyle.NameOnly; var typeNameFormat = new SymbolDisplayFormat( typeQualificationStyle: typeQualificationStyle, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); AddName(typeSymbol.ToDisplayString(typeNameFormat)); AddText("("); BuildParameterList(delegateInvokeMethod.Parameters); AddText(")"); if (typeSymbol.IsGenericType) { BuildGenericConstraints(typeSymbol); } } protected override void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options) { BuildTypeModifiers(typeSymbol); switch (typeSymbol.TypeKind) { case TypeKind.Enum: AddText("enum "); break; case TypeKind.Struct: AddText("struct "); break; case TypeKind.Interface: AddText("interface "); break; case TypeKind.Class: AddText("class "); break; default: Debug.Fail("Invalid type kind encountered: " + typeSymbol.TypeKind.ToString()); break; } var typeNameFormat = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); AddName(typeSymbol.ToDisplayString(typeNameFormat)); if (typeSymbol.TypeKind == TypeKind.Enum) { var underlyingType = typeSymbol.EnumUnderlyingType; if (underlyingType != null) { if (underlyingType.SpecialType != SpecialType.System_Int32) { AddText(" : "); AddTypeLink(underlyingType, LinkFlags.None); } } } else { var baseType = typeSymbol.BaseType; if (baseType != null) { if (baseType.SpecialType is not SpecialType.System_Object and not SpecialType.System_Delegate and not SpecialType.System_MulticastDelegate and not SpecialType.System_Enum and not SpecialType.System_ValueType) { AddText(" : "); AddTypeLink(baseType, LinkFlags.None); } } } if (typeSymbol.IsGenericType) { BuildGenericConstraints(typeSymbol); } } private void BuildAccessibility(ISymbol symbol) { switch (symbol.DeclaredAccessibility) { case Accessibility.Public: AddText("public "); break; case Accessibility.Private: AddText("private "); break; case Accessibility.Protected: AddText("protected "); break; case Accessibility.Internal: AddText("internal "); break; case Accessibility.ProtectedOrInternal: AddText("protected internal "); break; case Accessibility.ProtectedAndInternal: AddText("private protected "); break; default: AddText("internal "); break; } } private void BuildTypeModifiers(INamedTypeSymbol typeSymbol) { BuildAccessibility(typeSymbol); if (typeSymbol.IsStatic) { AddText("static "); } if (typeSymbol.IsAbstract && typeSymbol.TypeKind != TypeKind.Interface) { AddText("abstract "); } if (typeSymbol.IsSealed && typeSymbol.TypeKind != TypeKind.Struct && typeSymbol.TypeKind != TypeKind.Enum && typeSymbol.TypeKind != TypeKind.Delegate) { AddText("sealed "); } } protected override void BuildMethodDeclaration(IMethodSymbol methodSymbol, _VSOBJDESCOPTIONS options) { BuildMemberModifiers(methodSymbol); if (methodSymbol.MethodKind is not MethodKind.Constructor and not MethodKind.Destructor and not MethodKind.StaticConstructor and not MethodKind.Conversion) { AddTypeLink(methodSymbol.ReturnType, LinkFlags.None); AddText(" "); } if (methodSymbol.MethodKind == MethodKind.Conversion) { switch (methodSymbol.Name) { case WellKnownMemberNames.ImplicitConversionName: AddName("implicit operator "); break; case WellKnownMemberNames.ExplicitConversionName: AddName("explicit operator "); break; } AddTypeLink(methodSymbol.ReturnType, LinkFlags.None); } else { var methodNameFormat = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); AddName(methodSymbol.ToDisplayString(methodNameFormat)); } AddText("("); if (methodSymbol.IsExtensionMethod) { AddText("this "); } BuildParameterList(methodSymbol.Parameters); AddText(")"); if (methodSymbol.IsGenericMethod) { BuildGenericConstraints(methodSymbol); } } private void BuildMemberModifiers(ISymbol memberSymbol) { if (memberSymbol.ContainingType != null && memberSymbol.ContainingType.TypeKind == TypeKind.Interface) { return; } var methodSymbol = memberSymbol as IMethodSymbol; var fieldSymbol = memberSymbol as IFieldSymbol; if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.Destructor) { return; } if (fieldSymbol != null && fieldSymbol.ContainingType.TypeKind == TypeKind.Enum) { return; } // TODO: 'new' modifier isn't exposed on symbols. Do we need it? // Note: we don't display the access modifier for static constructors if (methodSymbol == null || methodSymbol.MethodKind != MethodKind.StaticConstructor) { BuildAccessibility(memberSymbol); } if (memberSymbol.RequiresUnsafeModifier()) { AddText("unsafe "); } // Note: we don't display 'static' for constant fields if (memberSymbol.IsStatic && (fieldSymbol == null || !fieldSymbol.IsConst)) { AddText("static "); } if (memberSymbol.IsExtern) { AddText("extern "); } if (fieldSymbol != null && fieldSymbol.IsReadOnly) { AddText("readonly "); } if (fieldSymbol != null && fieldSymbol.IsConst) { AddText("const "); } if (fieldSymbol != null && fieldSymbol.IsVolatile) { AddText("volatile "); } if (memberSymbol.IsAbstract) { AddText("abstract "); } else if (memberSymbol.IsOverride) { if (memberSymbol.IsSealed) { AddText("sealed "); } AddText("override "); } else if (memberSymbol.IsVirtual) { AddText("virtual "); } } private void BuildGenericConstraints(INamedTypeSymbol typeSymbol) { foreach (var typeParameterSymbol in typeSymbol.TypeParameters) { BuildConstraints(typeParameterSymbol); } } private void BuildGenericConstraints(IMethodSymbol methodSymbol) { foreach (var typeParameterSymbol in methodSymbol.TypeParameters) { BuildConstraints(typeParameterSymbol); } } private void BuildConstraints(ITypeParameterSymbol typeParameterSymbol) { if (typeParameterSymbol.ConstraintTypes.Length == 0 && !typeParameterSymbol.HasConstructorConstraint && !typeParameterSymbol.HasReferenceTypeConstraint && !typeParameterSymbol.HasValueTypeConstraint) { return; } AddLineBreak(); AddText("\t"); AddText("where "); AddName(typeParameterSymbol.Name); AddText(" : "); var isFirst = true; if (typeParameterSymbol.HasReferenceTypeConstraint) { if (!isFirst) { AddComma(); } AddText("class"); isFirst = false; } if (typeParameterSymbol.HasValueTypeConstraint) { if (!isFirst) { AddComma(); } AddText("struct"); isFirst = false; } foreach (var constraintType in typeParameterSymbol.ConstraintTypes) { if (!isFirst) { AddComma(); } AddTypeLink(constraintType, LinkFlags.None); isFirst = false; } if (typeParameterSymbol.HasConstructorConstraint) { if (!isFirst) { AddComma(); } AddText("new()"); } } private void BuildParameterList(ImmutableArray<IParameterSymbol> parameters) { var count = parameters.Length; if (count == 0) { return; } for (var i = 0; i < count; i++) { if (i > 0) { AddComma(); } var current = parameters[i]; if (current.IsOptional) { AddText("["); } if (current.RefKind == RefKind.Ref) { AddText("ref "); } else if (current.RefKind == RefKind.Out) { AddText("out "); } if (current.IsParams) { AddText("params "); } AddTypeLink(current.Type, LinkFlags.None); AddText(" "); AddParam(current.Name); if (current.HasExplicitDefaultValue) { AddText(" = "); if (current.ExplicitDefaultValue == null) { AddText("null"); } else { AddText(current.ExplicitDefaultValue.ToString()); } } if (current.IsOptional) { AddText("]"); } } } protected override void BuildFieldDeclaration(IFieldSymbol fieldSymbol, _VSOBJDESCOPTIONS options) { BuildMemberModifiers(fieldSymbol); if (fieldSymbol.ContainingType.TypeKind != TypeKind.Enum) { AddTypeLink(fieldSymbol.Type, LinkFlags.None); AddText(" "); } AddName(fieldSymbol.Name); } protected override void BuildPropertyDeclaration(IPropertySymbol propertySymbol, _VSOBJDESCOPTIONS options) { BuildMemberModifiers(propertySymbol); AddTypeLink(propertySymbol.Type, LinkFlags.None); AddText(" "); if (propertySymbol.IsIndexer) { AddName("this"); AddText("["); BuildParameterList(propertySymbol.Parameters); AddText("]"); } else { AddName(propertySymbol.Name); } AddText(" { "); if (propertySymbol.GetMethod != null) { if (propertySymbol.GetMethod.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { BuildAccessibility(propertySymbol.GetMethod); } AddText("get; "); } if (propertySymbol.SetMethod != null) { if (propertySymbol.SetMethod.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { BuildAccessibility(propertySymbol.SetMethod); } AddText("set; "); } AddText("}"); } protected override void BuildEventDeclaration(IEventSymbol eventSymbol, _VSOBJDESCOPTIONS options) { BuildMemberModifiers(eventSymbol); AddText("event "); AddTypeLink(eventSymbol.Type, LinkFlags.None); AddText(" "); AddName(eventSymbol.Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { internal class DescriptionBuilder : AbstractDescriptionBuilder { public DescriptionBuilder( IVsObjectBrowserDescription3 description, ObjectBrowserLibraryManager libraryManager, ObjectListItem listItem, Project project) : base(description, libraryManager, listItem, project) { } protected override void BuildNamespaceDeclaration(INamespaceSymbol namespaceSymbol, _VSOBJDESCOPTIONS options) { AddText("namespace "); AddName(namespaceSymbol.ToDisplayString()); } protected override void BuildDelegateDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options) { Debug.Assert(typeSymbol.TypeKind == TypeKind.Delegate); BuildTypeModifiers(typeSymbol); AddText("delegate "); var delegateInvokeMethod = typeSymbol.DelegateInvokeMethod; AddTypeLink(delegateInvokeMethod.ReturnType, LinkFlags.None); AddText(" "); var typeQualificationStyle = (options & _VSOBJDESCOPTIONS.ODO_USEFULLNAME) != 0 ? SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces : SymbolDisplayTypeQualificationStyle.NameOnly; var typeNameFormat = new SymbolDisplayFormat( typeQualificationStyle: typeQualificationStyle, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); AddName(typeSymbol.ToDisplayString(typeNameFormat)); AddText("("); BuildParameterList(delegateInvokeMethod.Parameters); AddText(")"); if (typeSymbol.IsGenericType) { BuildGenericConstraints(typeSymbol); } } protected override void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options) { BuildTypeModifiers(typeSymbol); switch (typeSymbol.TypeKind) { case TypeKind.Enum: AddText("enum "); break; case TypeKind.Struct: AddText("struct "); break; case TypeKind.Interface: AddText("interface "); break; case TypeKind.Class: AddText("class "); break; default: Debug.Fail("Invalid type kind encountered: " + typeSymbol.TypeKind.ToString()); break; } var typeNameFormat = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); AddName(typeSymbol.ToDisplayString(typeNameFormat)); if (typeSymbol.TypeKind == TypeKind.Enum) { var underlyingType = typeSymbol.EnumUnderlyingType; if (underlyingType != null) { if (underlyingType.SpecialType != SpecialType.System_Int32) { AddText(" : "); AddTypeLink(underlyingType, LinkFlags.None); } } } else { var baseType = typeSymbol.BaseType; if (baseType != null) { if (baseType.SpecialType is not SpecialType.System_Object and not SpecialType.System_Delegate and not SpecialType.System_MulticastDelegate and not SpecialType.System_Enum and not SpecialType.System_ValueType) { AddText(" : "); AddTypeLink(baseType, LinkFlags.None); } } } if (typeSymbol.IsGenericType) { BuildGenericConstraints(typeSymbol); } } private void BuildAccessibility(ISymbol symbol) { switch (symbol.DeclaredAccessibility) { case Accessibility.Public: AddText("public "); break; case Accessibility.Private: AddText("private "); break; case Accessibility.Protected: AddText("protected "); break; case Accessibility.Internal: AddText("internal "); break; case Accessibility.ProtectedOrInternal: AddText("protected internal "); break; case Accessibility.ProtectedAndInternal: AddText("private protected "); break; default: AddText("internal "); break; } } private void BuildTypeModifiers(INamedTypeSymbol typeSymbol) { BuildAccessibility(typeSymbol); if (typeSymbol.IsStatic) { AddText("static "); } if (typeSymbol.IsAbstract && typeSymbol.TypeKind != TypeKind.Interface) { AddText("abstract "); } if (typeSymbol.IsSealed && typeSymbol.TypeKind != TypeKind.Struct && typeSymbol.TypeKind != TypeKind.Enum && typeSymbol.TypeKind != TypeKind.Delegate) { AddText("sealed "); } } protected override void BuildMethodDeclaration(IMethodSymbol methodSymbol, _VSOBJDESCOPTIONS options) { BuildMemberModifiers(methodSymbol); if (methodSymbol.MethodKind is not MethodKind.Constructor and not MethodKind.Destructor and not MethodKind.StaticConstructor and not MethodKind.Conversion) { AddTypeLink(methodSymbol.ReturnType, LinkFlags.None); AddText(" "); } if (methodSymbol.MethodKind == MethodKind.Conversion) { switch (methodSymbol.Name) { case WellKnownMemberNames.ImplicitConversionName: AddName("implicit operator "); break; case WellKnownMemberNames.ExplicitConversionName: AddName("explicit operator "); break; } AddTypeLink(methodSymbol.ReturnType, LinkFlags.None); } else { var methodNameFormat = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); AddName(methodSymbol.ToDisplayString(methodNameFormat)); } AddText("("); if (methodSymbol.IsExtensionMethod) { AddText("this "); } BuildParameterList(methodSymbol.Parameters); AddText(")"); if (methodSymbol.IsGenericMethod) { BuildGenericConstraints(methodSymbol); } } private void BuildMemberModifiers(ISymbol memberSymbol) { if (memberSymbol.ContainingType != null && memberSymbol.ContainingType.TypeKind == TypeKind.Interface) { return; } var methodSymbol = memberSymbol as IMethodSymbol; var fieldSymbol = memberSymbol as IFieldSymbol; if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.Destructor) { return; } if (fieldSymbol != null && fieldSymbol.ContainingType.TypeKind == TypeKind.Enum) { return; } // TODO: 'new' modifier isn't exposed on symbols. Do we need it? // Note: we don't display the access modifier for static constructors if (methodSymbol == null || methodSymbol.MethodKind != MethodKind.StaticConstructor) { BuildAccessibility(memberSymbol); } if (memberSymbol.RequiresUnsafeModifier()) { AddText("unsafe "); } // Note: we don't display 'static' for constant fields if (memberSymbol.IsStatic && (fieldSymbol == null || !fieldSymbol.IsConst)) { AddText("static "); } if (memberSymbol.IsExtern) { AddText("extern "); } if (fieldSymbol != null && fieldSymbol.IsReadOnly) { AddText("readonly "); } if (fieldSymbol != null && fieldSymbol.IsConst) { AddText("const "); } if (fieldSymbol != null && fieldSymbol.IsVolatile) { AddText("volatile "); } if (memberSymbol.IsAbstract) { AddText("abstract "); } else if (memberSymbol.IsOverride) { if (memberSymbol.IsSealed) { AddText("sealed "); } AddText("override "); } else if (memberSymbol.IsVirtual) { AddText("virtual "); } } private void BuildGenericConstraints(INamedTypeSymbol typeSymbol) { foreach (var typeParameterSymbol in typeSymbol.TypeParameters) { BuildConstraints(typeParameterSymbol); } } private void BuildGenericConstraints(IMethodSymbol methodSymbol) { foreach (var typeParameterSymbol in methodSymbol.TypeParameters) { BuildConstraints(typeParameterSymbol); } } private void BuildConstraints(ITypeParameterSymbol typeParameterSymbol) { if (typeParameterSymbol.ConstraintTypes.Length == 0 && !typeParameterSymbol.HasConstructorConstraint && !typeParameterSymbol.HasReferenceTypeConstraint && !typeParameterSymbol.HasValueTypeConstraint) { return; } AddLineBreak(); AddText("\t"); AddText("where "); AddName(typeParameterSymbol.Name); AddText(" : "); var isFirst = true; if (typeParameterSymbol.HasReferenceTypeConstraint) { if (!isFirst) { AddComma(); } AddText("class"); isFirst = false; } if (typeParameterSymbol.HasValueTypeConstraint) { if (!isFirst) { AddComma(); } AddText("struct"); isFirst = false; } foreach (var constraintType in typeParameterSymbol.ConstraintTypes) { if (!isFirst) { AddComma(); } AddTypeLink(constraintType, LinkFlags.None); isFirst = false; } if (typeParameterSymbol.HasConstructorConstraint) { if (!isFirst) { AddComma(); } AddText("new()"); } } private void BuildParameterList(ImmutableArray<IParameterSymbol> parameters) { var count = parameters.Length; if (count == 0) { return; } for (var i = 0; i < count; i++) { if (i > 0) { AddComma(); } var current = parameters[i]; if (current.IsOptional) { AddText("["); } if (current.RefKind == RefKind.Ref) { AddText("ref "); } else if (current.RefKind == RefKind.Out) { AddText("out "); } if (current.IsParams) { AddText("params "); } AddTypeLink(current.Type, LinkFlags.None); AddText(" "); AddParam(current.Name); if (current.HasExplicitDefaultValue) { AddText(" = "); if (current.ExplicitDefaultValue == null) { AddText("null"); } else { AddText(current.ExplicitDefaultValue.ToString()); } } if (current.IsOptional) { AddText("]"); } } } protected override void BuildFieldDeclaration(IFieldSymbol fieldSymbol, _VSOBJDESCOPTIONS options) { BuildMemberModifiers(fieldSymbol); if (fieldSymbol.ContainingType.TypeKind != TypeKind.Enum) { AddTypeLink(fieldSymbol.Type, LinkFlags.None); AddText(" "); } AddName(fieldSymbol.Name); } protected override void BuildPropertyDeclaration(IPropertySymbol propertySymbol, _VSOBJDESCOPTIONS options) { BuildMemberModifiers(propertySymbol); AddTypeLink(propertySymbol.Type, LinkFlags.None); AddText(" "); if (propertySymbol.IsIndexer) { AddName("this"); AddText("["); BuildParameterList(propertySymbol.Parameters); AddText("]"); } else { AddName(propertySymbol.Name); } AddText(" { "); if (propertySymbol.GetMethod != null) { if (propertySymbol.GetMethod.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { BuildAccessibility(propertySymbol.GetMethod); } AddText("get; "); } if (propertySymbol.SetMethod != null) { if (propertySymbol.SetMethod.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { BuildAccessibility(propertySymbol.SetMethod); } AddText("set; "); } AddText("}"); } protected override void BuildEventDeclaration(IEventSymbol eventSymbol, _VSOBJDESCOPTIONS options) { BuildMemberModifiers(eventSymbol); AddText("event "); AddTypeLink(eventSymbol.Type, LinkFlags.None); AddText(" "); AddName(eventSymbol.Name); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.NodesAndTokensToReduceComputer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicSimplificationService Inherits AbstractSimplificationService(Of ExpressionSyntax, ExecutableStatementSyntax, CrefReferenceSyntax) Private Class NodesAndTokensToReduceComputer Inherits VisualBasicSyntaxRewriter Private ReadOnly _nodesAndTokensToReduce As List(Of NodeOrTokenToReduce) Private ReadOnly _isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean) Private Shared ReadOnly s_containsAnnotations As Func(Of SyntaxNode, Boolean) = Function(n) n.ContainsAnnotations Private Shared ReadOnly s_hasSimplifierAnnotation As Func(Of SyntaxNodeOrToken, Boolean) = Function(n) n.HasAnnotation(Simplifier.Annotation) Private _simplifyAllDescendants As Boolean Private _insideSpeculatedNode As Boolean ''' <summary> ''' Computes a list of nodes and tokens that need to be reduced in the given syntax root. ''' </summary> Public Shared Function Compute(root As SyntaxNode, isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) As ImmutableArray(Of NodeOrTokenToReduce) Dim reduceNodeComputer = New NodesAndTokensToReduceComputer(isNodeOrTokenOutsideSimplifySpans) reduceNodeComputer.Visit(root) Return reduceNodeComputer._nodesAndTokensToReduce.ToImmutableArray() End Function Private Sub New(isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) MyBase.New(visitIntoStructuredTrivia:=True) Me._isNodeOrTokenOutsideSimplifySpans = isNodeOrTokenOutsideSimplifySpans Me._nodesAndTokensToReduce = New List(Of NodeOrTokenToReduce)() Me._simplifyAllDescendants = False Me._insideSpeculatedNode = False End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode If node Is Nothing Then Return node End If If Me._isNodeOrTokenOutsideSimplifySpans(node) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes is within a simplification span, but this node Is outside all simplification spans. ' Add DontSimplifyAnnotation to node to ensure it doesn't get simplified. Return node.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return node End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse node.HasAnnotation(Simplifier.Annotation) If Not Me._insideSpeculatedNode AndAlso SpeculationAnalyzer.CanSpeculateOnNode(node) Then If Me._simplifyAllDescendants OrElse node.DescendantNodesAndTokens(s_containsAnnotations, descendIntoTrivia:=True).Any(s_hasSimplifierAnnotation) Then Me._insideSpeculatedNode = True Dim rewrittenNode = MyBase.Visit(node) Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(rewrittenNode, _simplifyAllDescendants, node)) Me._insideSpeculatedNode = False End If ElseIf node.ContainsAnnotations OrElse savedSimplifyAllDescendants Then If Not Me._insideSpeculatedNode AndAlso IsNodeVariableDeclaratorOfFieldDeclaration(node) AndAlso Me._simplifyAllDescendants Then Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(node, False, node, False)) End If node = MyBase.Visit(node) End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return node End Function Private Shared Function IsNodeVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As Boolean Return node IsNot Nothing AndAlso node.Kind() = SyntaxKind.VariableDeclarator AndAlso node.Parent IsNot Nothing AndAlso node.Parent.Kind() = SyntaxKind.FieldDeclaration End Function Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken If Me._isNodeOrTokenOutsideSimplifySpans(token) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes is within a simplification span, but this token Is outside all simplification spans. ' Add DontSimplifyAnnotation to token to ensure it doesn't get simplified. Return token.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return token End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse token.HasAnnotation(Simplifier.Annotation) If Me._simplifyAllDescendants AndAlso Not Me._insideSpeculatedNode AndAlso token.Kind <> SyntaxKind.None Then Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(token, simplifyAllDescendants:=True, originalNodeOrToken:=token)) End If If token.ContainsAnnotations OrElse savedSimplifyAllDescendants Then token = MyBase.VisitToken(token) End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return token End Function Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.HasStructure Then Dim savedInsideSpeculatedNode = Me._insideSpeculatedNode Me._insideSpeculatedNode = False MyBase.VisitTrivia(trivia) Me._insideSpeculatedNode = savedInsideSpeculatedNode End If Return trivia End Function Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, MethodBlockSyntax).Update(node.Kind, DirectCast(b, MethodStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, OperatorBlockSyntax).Update(DirectCast(b, OperatorStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, ConstructorBlockSyntax).Update(DirectCast(b, SubNewStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, AccessorBlockSyntax).Update(node.Kind, DirectCast(b, AccessorStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Private Function VisitMethodBlockBaseSyntax(node As MethodBlockBaseSyntax, updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax)) As MethodBlockBaseSyntax If Me._isNodeOrTokenOutsideSimplifySpans(node) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes Is within a simplification span, but this node Is outside all simplification spans. ' Add DontSimplifyAnnotation to node to ensure it doesn't get simplified. Return node.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return node End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse node.HasAnnotation(Simplifier.Annotation) Dim begin = DirectCast(Visit(node.BlockStatement), MethodBaseSyntax) Dim endStatement = DirectCast(Visit(node.EndBlockStatement), EndBlockStatementSyntax) ' Certain reducers for VB (escaping, parentheses) require to operate on the entire method body, rather than individual statements. ' Hence, we need to reduce the entire method body as a single unit. ' However, there is no SyntaxNode for the method body or statement list, hence we add the MethodBlockBaseSyntax to the list of nodes to be reduced. ' Subsequently, when the AbstractReducer is handed a MethodBlockBaseSyntax, it will reduce only the statement list inside it. If Me._simplifyAllDescendants OrElse node.Statements.Any(Function(s) s.DescendantNodesAndTokensAndSelf(s_containsAnnotations, descendIntoTrivia:=True).Any(s_hasSimplifierAnnotation)) Then Me._insideSpeculatedNode = True Dim statements = VisitList(node.Statements) Dim rewrittenNode = updateFunc(node, node.BlockStatement, statements, node.EndBlockStatement) Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(rewrittenNode, Me._simplifyAllDescendants, node)) Me._insideSpeculatedNode = False End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return node 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.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicSimplificationService Inherits AbstractSimplificationService(Of ExpressionSyntax, ExecutableStatementSyntax, CrefReferenceSyntax) Private Class NodesAndTokensToReduceComputer Inherits VisualBasicSyntaxRewriter Private ReadOnly _nodesAndTokensToReduce As List(Of NodeOrTokenToReduce) Private ReadOnly _isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean) Private Shared ReadOnly s_containsAnnotations As Func(Of SyntaxNode, Boolean) = Function(n) n.ContainsAnnotations Private Shared ReadOnly s_hasSimplifierAnnotation As Func(Of SyntaxNodeOrToken, Boolean) = Function(n) n.HasAnnotation(Simplifier.Annotation) Private _simplifyAllDescendants As Boolean Private _insideSpeculatedNode As Boolean ''' <summary> ''' Computes a list of nodes and tokens that need to be reduced in the given syntax root. ''' </summary> Public Shared Function Compute(root As SyntaxNode, isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) As ImmutableArray(Of NodeOrTokenToReduce) Dim reduceNodeComputer = New NodesAndTokensToReduceComputer(isNodeOrTokenOutsideSimplifySpans) reduceNodeComputer.Visit(root) Return reduceNodeComputer._nodesAndTokensToReduce.ToImmutableArray() End Function Private Sub New(isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) MyBase.New(visitIntoStructuredTrivia:=True) Me._isNodeOrTokenOutsideSimplifySpans = isNodeOrTokenOutsideSimplifySpans Me._nodesAndTokensToReduce = New List(Of NodeOrTokenToReduce)() Me._simplifyAllDescendants = False Me._insideSpeculatedNode = False End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode If node Is Nothing Then Return node End If If Me._isNodeOrTokenOutsideSimplifySpans(node) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes is within a simplification span, but this node Is outside all simplification spans. ' Add DontSimplifyAnnotation to node to ensure it doesn't get simplified. Return node.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return node End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse node.HasAnnotation(Simplifier.Annotation) If Not Me._insideSpeculatedNode AndAlso SpeculationAnalyzer.CanSpeculateOnNode(node) Then If Me._simplifyAllDescendants OrElse node.DescendantNodesAndTokens(s_containsAnnotations, descendIntoTrivia:=True).Any(s_hasSimplifierAnnotation) Then Me._insideSpeculatedNode = True Dim rewrittenNode = MyBase.Visit(node) Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(rewrittenNode, _simplifyAllDescendants, node)) Me._insideSpeculatedNode = False End If ElseIf node.ContainsAnnotations OrElse savedSimplifyAllDescendants Then If Not Me._insideSpeculatedNode AndAlso IsNodeVariableDeclaratorOfFieldDeclaration(node) AndAlso Me._simplifyAllDescendants Then Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(node, False, node, False)) End If node = MyBase.Visit(node) End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return node End Function Private Shared Function IsNodeVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As Boolean Return node IsNot Nothing AndAlso node.Kind() = SyntaxKind.VariableDeclarator AndAlso node.Parent IsNot Nothing AndAlso node.Parent.Kind() = SyntaxKind.FieldDeclaration End Function Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken If Me._isNodeOrTokenOutsideSimplifySpans(token) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes is within a simplification span, but this token Is outside all simplification spans. ' Add DontSimplifyAnnotation to token to ensure it doesn't get simplified. Return token.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return token End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse token.HasAnnotation(Simplifier.Annotation) If Me._simplifyAllDescendants AndAlso Not Me._insideSpeculatedNode AndAlso token.Kind <> SyntaxKind.None Then Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(token, simplifyAllDescendants:=True, originalNodeOrToken:=token)) End If If token.ContainsAnnotations OrElse savedSimplifyAllDescendants Then token = MyBase.VisitToken(token) End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return token End Function Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.HasStructure Then Dim savedInsideSpeculatedNode = Me._insideSpeculatedNode Me._insideSpeculatedNode = False MyBase.VisitTrivia(trivia) Me._insideSpeculatedNode = savedInsideSpeculatedNode End If Return trivia End Function Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, MethodBlockSyntax).Update(node.Kind, DirectCast(b, MethodStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, OperatorBlockSyntax).Update(DirectCast(b, OperatorStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, ConstructorBlockSyntax).Update(DirectCast(b, SubNewStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, AccessorBlockSyntax).Update(node.Kind, DirectCast(b, AccessorStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Private Function VisitMethodBlockBaseSyntax(node As MethodBlockBaseSyntax, updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax)) As MethodBlockBaseSyntax If Me._isNodeOrTokenOutsideSimplifySpans(node) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes Is within a simplification span, but this node Is outside all simplification spans. ' Add DontSimplifyAnnotation to node to ensure it doesn't get simplified. Return node.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return node End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse node.HasAnnotation(Simplifier.Annotation) Dim begin = DirectCast(Visit(node.BlockStatement), MethodBaseSyntax) Dim endStatement = DirectCast(Visit(node.EndBlockStatement), EndBlockStatementSyntax) ' Certain reducers for VB (escaping, parentheses) require to operate on the entire method body, rather than individual statements. ' Hence, we need to reduce the entire method body as a single unit. ' However, there is no SyntaxNode for the method body or statement list, hence we add the MethodBlockBaseSyntax to the list of nodes to be reduced. ' Subsequently, when the AbstractReducer is handed a MethodBlockBaseSyntax, it will reduce only the statement list inside it. If Me._simplifyAllDescendants OrElse node.Statements.Any(Function(s) s.DescendantNodesAndTokensAndSelf(s_containsAnnotations, descendIntoTrivia:=True).Any(s_hasSimplifierAnnotation)) Then Me._insideSpeculatedNode = True Dim statements = VisitList(node.Statements) Dim rewrittenNode = updateFunc(node, node.BlockStatement, statements, node.EndBlockStatement) Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(rewrittenNode, Me._simplifyAllDescendants, node)) Me._insideSpeculatedNode = False End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return node End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Test/Symbol/Symbols/MockSymbolTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Text; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolTests { [Fact] public void TestArrayType() { CSharpCompilation compilation = CSharpCompilation.Create("Test"); NamedTypeSymbol elementType = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>()); // this can be any type. ArrayTypeSymbol ats1 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 1); Assert.Equal(1, ats1.Rank); Assert.True(ats1.IsSZArray); Assert.Same(elementType, ats1.ElementType); Assert.Equal(SymbolKind.ArrayType, ats1.Kind); Assert.True(ats1.IsReferenceType); Assert.False(ats1.IsValueType); Assert.Equal("TestClass[]", ats1.ToTestDisplayString()); ArrayTypeSymbol ats2 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 2); Assert.Equal(2, ats2.Rank); Assert.Same(elementType, ats2.ElementType); Assert.Equal(SymbolKind.ArrayType, ats2.Kind); Assert.True(ats2.IsReferenceType); Assert.False(ats2.IsValueType); Assert.Equal("TestClass[,]", ats2.ToTestDisplayString()); ArrayTypeSymbol ats3 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 3); Assert.Equal(3, ats3.Rank); Assert.Equal("TestClass[,,]", ats3.ToTestDisplayString()); } [Fact] public void TestPointerType() { NamedTypeSymbol pointedAtType = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>()); // this can be any type. PointerTypeSymbol pts1 = new PointerTypeSymbol(TypeWithAnnotations.Create(pointedAtType)); Assert.Same(pointedAtType, pts1.PointedAtType); Assert.Equal(SymbolKind.PointerType, pts1.Kind); Assert.False(pts1.IsReferenceType); Assert.True(pts1.IsValueType); Assert.Equal("TestClass*", pts1.ToTestDisplayString()); } [Fact] public void TestMissingMetadataSymbol() { AssemblyIdentity missingAssemblyId = new AssemblyIdentity("goo"); AssemblySymbol assem = new MockAssemblySymbol("banana"); ModuleSymbol module = new MissingModuleSymbol(assem, ordinal: -1); NamedTypeSymbol container = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>(), TypeKind.Class); var mms1 = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(missingAssemblyId).Modules[0], "Elvis", "Lives", 2, true); Assert.Equal(2, mms1.Arity); Assert.Equal("Elvis", mms1.NamespaceName); Assert.Equal("Lives", mms1.Name); Assert.Equal("Elvis.Lives<,>[missing]", mms1.ToTestDisplayString()); Assert.Equal("goo", mms1.ContainingAssembly.Identity.Name); var mms2 = new MissingMetadataTypeSymbol.TopLevel(module, "Elvis.Is", "Cool", 0, true); Assert.Equal(0, mms2.Arity); Assert.Equal("Elvis.Is", mms2.NamespaceName); Assert.Equal("Cool", mms2.Name); Assert.Equal("Elvis.Is.Cool[missing]", mms2.ToTestDisplayString()); Assert.Same(assem, mms2.ContainingAssembly); // TODO: Add test for 3rd constructor. } [Fact] public void TestNamespaceExtent() { AssemblySymbol assem1 = new MockAssemblySymbol("goo"); NamespaceExtent ne1 = new NamespaceExtent(assem1); Assert.Equal(NamespaceKind.Assembly, ne1.Kind); Assert.Same(ne1.Assembly, assem1); CSharpCompilation compilation = CSharpCompilation.Create("Test"); NamespaceExtent ne2 = new NamespaceExtent(compilation); Assert.IsType<CSharpCompilation>(ne2.Compilation); Assert.Throws<InvalidOperationException>(() => ne1.Compilation); } private Symbol CreateMockSymbol(NamespaceExtent extent, XElement xel) { Symbol result; var childSymbols = from childElement in xel.Elements() select CreateMockSymbol(extent, childElement); string name = xel.Attribute("name").Value; switch (xel.Name.LocalName) { case "ns": result = new MockNamespaceSymbol(name, extent, childSymbols); break; case "class": result = new MockNamedTypeSymbol(name, childSymbols, TypeKind.Class); break; default: throw new InvalidOperationException("unexpected xml element"); } foreach (IMockSymbol child in childSymbols) { child.SetContainer(result); } return result; } private void DumpSymbol(Symbol sym, StringBuilder builder, int level) { if (sym is NamespaceSymbol) { builder.AppendFormat("namespace {0} [{1}]", sym.Name, (sym as NamespaceSymbol).Extent); } else if (sym is NamedTypeSymbol) { builder.AppendFormat("{0} {1}", (sym as NamedTypeSymbol).TypeKind.ToString().ToLower(), sym.Name); } else { throw new InvalidOperationException("Unexpected symbol kind"); } if (sym is NamespaceOrTypeSymbol namespaceOrType && namespaceOrType.GetMembers().Any()) { builder.AppendLine(" { "); var q = from c in namespaceOrType.GetMembers() orderby c.Name select c; foreach (Symbol child in q) { for (int i = 0; i <= level; ++i) { builder.Append(" "); } DumpSymbol(child, builder, level + 1); builder.AppendLine(); } for (int i = 0; i < level; ++i) { builder.Append(" "); } builder.Append("}"); } } private string DumpSymbol(Symbol sym) { StringBuilder builder = new StringBuilder(); DumpSymbol(sym, builder, 0); return builder.ToString(); } [Fact] public void TestMergedNamespaces() { NamespaceSymbol root1 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem1")), XElement.Parse( @"<ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'/> <ns name='F'> <ns name='G'/> </ns> </ns> <ns name='B'/> <ns name='C'/> <ns name='U'/> <class name='X'/> </ns>")); NamespaceSymbol root2 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem2")), XElement.Parse( @"<ns name=''> <ns name='B'> <ns name='K'/> </ns> <ns name='C'/> <class name='X'/> <class name='Y'/> </ns>")); NamespaceSymbol root3 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem3")), XElement.Parse( @"<ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'> <ns name='H'/> </ns> </ns> <ns name='B'> <ns name='K'> <ns name='L'/> <class name='L'/> </ns> </ns> <class name='Z'/> </ns>")); NamespaceSymbol merged = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged")), null, new NamespaceSymbol[] { root1, root2, root3 }.AsImmutable()); string expected = @"namespace [Assembly: Merged] { namespace A [Assembly: Merged] { namespace D [Assembly: Merged] namespace E [Assembly: Merged] { namespace H [Assembly: Assem3] } namespace F [Assembly: Assem1] { namespace G [Assembly: Assem1] } } namespace B [Assembly: Merged] { namespace K [Assembly: Merged] { class L namespace L [Assembly: Assem3] } } namespace C [Assembly: Merged] namespace U [Assembly: Assem1] class X class X class Y class Z }".Replace("Assembly: Merged", "Assembly: Merged, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") .Replace("Assembly: Assem1", "Assembly: Assem1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") .Replace("Assembly: Assem3", "Assembly: Assem3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); Assert.Equal(expected, DumpSymbol(merged)); NamespaceSymbol merged2 = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged2")), null, new NamespaceSymbol[] { root1 }.AsImmutable()); Assert.Same(merged2, root1); } } internal interface IMockSymbol { void SetContainer(Symbol container); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Text; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolTests { [Fact] public void TestArrayType() { CSharpCompilation compilation = CSharpCompilation.Create("Test"); NamedTypeSymbol elementType = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>()); // this can be any type. ArrayTypeSymbol ats1 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 1); Assert.Equal(1, ats1.Rank); Assert.True(ats1.IsSZArray); Assert.Same(elementType, ats1.ElementType); Assert.Equal(SymbolKind.ArrayType, ats1.Kind); Assert.True(ats1.IsReferenceType); Assert.False(ats1.IsValueType); Assert.Equal("TestClass[]", ats1.ToTestDisplayString()); ArrayTypeSymbol ats2 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 2); Assert.Equal(2, ats2.Rank); Assert.Same(elementType, ats2.ElementType); Assert.Equal(SymbolKind.ArrayType, ats2.Kind); Assert.True(ats2.IsReferenceType); Assert.False(ats2.IsValueType); Assert.Equal("TestClass[,]", ats2.ToTestDisplayString()); ArrayTypeSymbol ats3 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 3); Assert.Equal(3, ats3.Rank); Assert.Equal("TestClass[,,]", ats3.ToTestDisplayString()); } [Fact] public void TestPointerType() { NamedTypeSymbol pointedAtType = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>()); // this can be any type. PointerTypeSymbol pts1 = new PointerTypeSymbol(TypeWithAnnotations.Create(pointedAtType)); Assert.Same(pointedAtType, pts1.PointedAtType); Assert.Equal(SymbolKind.PointerType, pts1.Kind); Assert.False(pts1.IsReferenceType); Assert.True(pts1.IsValueType); Assert.Equal("TestClass*", pts1.ToTestDisplayString()); } [Fact] public void TestMissingMetadataSymbol() { AssemblyIdentity missingAssemblyId = new AssemblyIdentity("goo"); AssemblySymbol assem = new MockAssemblySymbol("banana"); ModuleSymbol module = new MissingModuleSymbol(assem, ordinal: -1); NamedTypeSymbol container = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>(), TypeKind.Class); var mms1 = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(missingAssemblyId).Modules[0], "Elvis", "Lives", 2, true); Assert.Equal(2, mms1.Arity); Assert.Equal("Elvis", mms1.NamespaceName); Assert.Equal("Lives", mms1.Name); Assert.Equal("Elvis.Lives<,>[missing]", mms1.ToTestDisplayString()); Assert.Equal("goo", mms1.ContainingAssembly.Identity.Name); var mms2 = new MissingMetadataTypeSymbol.TopLevel(module, "Elvis.Is", "Cool", 0, true); Assert.Equal(0, mms2.Arity); Assert.Equal("Elvis.Is", mms2.NamespaceName); Assert.Equal("Cool", mms2.Name); Assert.Equal("Elvis.Is.Cool[missing]", mms2.ToTestDisplayString()); Assert.Same(assem, mms2.ContainingAssembly); // TODO: Add test for 3rd constructor. } [Fact] public void TestNamespaceExtent() { AssemblySymbol assem1 = new MockAssemblySymbol("goo"); NamespaceExtent ne1 = new NamespaceExtent(assem1); Assert.Equal(NamespaceKind.Assembly, ne1.Kind); Assert.Same(ne1.Assembly, assem1); CSharpCompilation compilation = CSharpCompilation.Create("Test"); NamespaceExtent ne2 = new NamespaceExtent(compilation); Assert.IsType<CSharpCompilation>(ne2.Compilation); Assert.Throws<InvalidOperationException>(() => ne1.Compilation); } private Symbol CreateMockSymbol(NamespaceExtent extent, XElement xel) { Symbol result; var childSymbols = from childElement in xel.Elements() select CreateMockSymbol(extent, childElement); string name = xel.Attribute("name").Value; switch (xel.Name.LocalName) { case "ns": result = new MockNamespaceSymbol(name, extent, childSymbols); break; case "class": result = new MockNamedTypeSymbol(name, childSymbols, TypeKind.Class); break; default: throw new InvalidOperationException("unexpected xml element"); } foreach (IMockSymbol child in childSymbols) { child.SetContainer(result); } return result; } private void DumpSymbol(Symbol sym, StringBuilder builder, int level) { if (sym is NamespaceSymbol) { builder.AppendFormat("namespace {0} [{1}]", sym.Name, (sym as NamespaceSymbol).Extent); } else if (sym is NamedTypeSymbol) { builder.AppendFormat("{0} {1}", (sym as NamedTypeSymbol).TypeKind.ToString().ToLower(), sym.Name); } else { throw new InvalidOperationException("Unexpected symbol kind"); } if (sym is NamespaceOrTypeSymbol namespaceOrType && namespaceOrType.GetMembers().Any()) { builder.AppendLine(" { "); var q = from c in namespaceOrType.GetMembers() orderby c.Name select c; foreach (Symbol child in q) { for (int i = 0; i <= level; ++i) { builder.Append(" "); } DumpSymbol(child, builder, level + 1); builder.AppendLine(); } for (int i = 0; i < level; ++i) { builder.Append(" "); } builder.Append("}"); } } private string DumpSymbol(Symbol sym) { StringBuilder builder = new StringBuilder(); DumpSymbol(sym, builder, 0); return builder.ToString(); } [Fact] public void TestMergedNamespaces() { NamespaceSymbol root1 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem1")), XElement.Parse( @"<ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'/> <ns name='F'> <ns name='G'/> </ns> </ns> <ns name='B'/> <ns name='C'/> <ns name='U'/> <class name='X'/> </ns>")); NamespaceSymbol root2 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem2")), XElement.Parse( @"<ns name=''> <ns name='B'> <ns name='K'/> </ns> <ns name='C'/> <class name='X'/> <class name='Y'/> </ns>")); NamespaceSymbol root3 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem3")), XElement.Parse( @"<ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'> <ns name='H'/> </ns> </ns> <ns name='B'> <ns name='K'> <ns name='L'/> <class name='L'/> </ns> </ns> <class name='Z'/> </ns>")); NamespaceSymbol merged = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged")), null, new NamespaceSymbol[] { root1, root2, root3 }.AsImmutable()); string expected = @"namespace [Assembly: Merged] { namespace A [Assembly: Merged] { namespace D [Assembly: Merged] namespace E [Assembly: Merged] { namespace H [Assembly: Assem3] } namespace F [Assembly: Assem1] { namespace G [Assembly: Assem1] } } namespace B [Assembly: Merged] { namespace K [Assembly: Merged] { class L namespace L [Assembly: Assem3] } } namespace C [Assembly: Merged] namespace U [Assembly: Assem1] class X class X class Y class Z }".Replace("Assembly: Merged", "Assembly: Merged, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") .Replace("Assembly: Assem1", "Assembly: Assem1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") .Replace("Assembly: Assem3", "Assembly: Assem3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); Assert.Equal(expected, DumpSymbol(merged)); NamespaceSymbol merged2 = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged2")), null, new NamespaceSymbol[] { root1 }.AsImmutable()); Assert.Same(merged2, root1); } } internal interface IMockSymbol { void SetContainer(Symbol container); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Core/Portable/PEWriter/ITypeReferenceExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using System.Text; namespace Microsoft.Cci { internal static class ITypeReferenceExtensions { internal static void GetConsolidatedTypeArguments(this ITypeReference typeReference, ArrayBuilder<ITypeReference> consolidatedTypeArguments, EmitContext context) { INestedTypeReference? nestedTypeReference = typeReference.AsNestedTypeReference; nestedTypeReference?.GetContainingType(context).GetConsolidatedTypeArguments(consolidatedTypeArguments, context); IGenericTypeInstanceReference? genTypeInstance = typeReference.AsGenericTypeInstanceReference; if (genTypeInstance != null) { consolidatedTypeArguments.AddRange(genTypeInstance.GetGenericArguments(context)); } } internal static ITypeReference GetUninstantiatedGenericType(this ITypeReference typeReference, EmitContext context) { IGenericTypeInstanceReference? genericTypeInstanceReference = typeReference.AsGenericTypeInstanceReference; if (genericTypeInstanceReference != null) { return genericTypeInstanceReference.GetGenericType(context); } ISpecializedNestedTypeReference? specializedNestedType = typeReference.AsSpecializedNestedTypeReference; if (specializedNestedType != null) { return specializedNestedType.GetUnspecializedVersion(context); } return typeReference; } internal static bool IsTypeSpecification(this ITypeReference typeReference) { INestedTypeReference? nestedTypeReference = typeReference.AsNestedTypeReference; if (nestedTypeReference != null) { return nestedTypeReference.AsSpecializedNestedTypeReference != null || nestedTypeReference.AsGenericTypeInstanceReference != null; } return typeReference.AsNamespaceTypeReference == null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using System.Text; namespace Microsoft.Cci { internal static class ITypeReferenceExtensions { internal static void GetConsolidatedTypeArguments(this ITypeReference typeReference, ArrayBuilder<ITypeReference> consolidatedTypeArguments, EmitContext context) { INestedTypeReference? nestedTypeReference = typeReference.AsNestedTypeReference; nestedTypeReference?.GetContainingType(context).GetConsolidatedTypeArguments(consolidatedTypeArguments, context); IGenericTypeInstanceReference? genTypeInstance = typeReference.AsGenericTypeInstanceReference; if (genTypeInstance != null) { consolidatedTypeArguments.AddRange(genTypeInstance.GetGenericArguments(context)); } } internal static ITypeReference GetUninstantiatedGenericType(this ITypeReference typeReference, EmitContext context) { IGenericTypeInstanceReference? genericTypeInstanceReference = typeReference.AsGenericTypeInstanceReference; if (genericTypeInstanceReference != null) { return genericTypeInstanceReference.GetGenericType(context); } ISpecializedNestedTypeReference? specializedNestedType = typeReference.AsSpecializedNestedTypeReference; if (specializedNestedType != null) { return specializedNestedType.GetUnspecializedVersion(context); } return typeReference; } internal static bool IsTypeSpecification(this ITypeReference typeReference) { INestedTypeReference? nestedTypeReference = typeReference.AsNestedTypeReference; if (nestedTypeReference != null) { return nestedTypeReference.AsSpecializedNestedTypeReference != null || nestedTypeReference.AsGenericTypeInstanceReference != null; } return typeReference.AsNamespaceTypeReference == null; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/AnalyzerConfigOptionsExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; #if CODE_STYLE using TOption = Microsoft.CodeAnalysis.Options.IOption2; #else using TOption = Microsoft.CodeAnalysis.Options.IOption; #endif namespace Microsoft.CodeAnalysis { internal static class AnalyzerConfigOptionsExtensions { #if CODE_STYLE public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption2<T> option, string language) { // Language is not used for .editorconfig lookups _ = language; return GetOption(analyzerConfigOptions, option); } #else public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, Options.Option<T> option) => GetOptionWithAssertOnFailure<T>(analyzerConfigOptions, option); public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, Options.PerLanguageOption<T> option) => GetOptionWithAssertOnFailure<T>(analyzerConfigOptions, option); #endif public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, Option2<T> option) => GetOptionWithAssertOnFailure<T>(analyzerConfigOptions, option); public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption2<T> option) => GetOptionWithAssertOnFailure<T>(analyzerConfigOptions, option); private static T GetOptionWithAssertOnFailure<T>(AnalyzerConfigOptions analyzerConfigOptions, TOption option) { if (!TryGetEditorConfigOptionOrDefault(analyzerConfigOptions, option, out T value)) { // There are couple of reasons this assert might fire: // 1. Attempting to access an option which does not have an IEditorConfigStorageLocation. // 2. Attempting to access an option which is not exposed from any option provider, i.e. IOptionProvider.Options. Debug.Fail("Failed to find a .editorconfig key for the option."); value = (T)option.DefaultValue!; } return value; } public static bool TryGetEditorConfigOptionOrDefault<T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, out T value) => TryGetEditorConfigOption(analyzerConfigOptions, option, useDefaultIfMissing: true, out value!); public static bool TryGetEditorConfigOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, [MaybeNullWhen(false)] out T value) => TryGetEditorConfigOption(analyzerConfigOptions, option, useDefaultIfMissing: false, out value); private static bool TryGetEditorConfigOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, bool useDefaultIfMissing, out T? value) { var hasEditorConfigStorage = false; foreach (var storageLocation in option.StorageLocations) { // This code path will avoid allocating a Dictionary wrapper since we can get direct access to the KeyName. if (storageLocation is EditorConfigStorageLocation<T> editorConfigStorageLocation && analyzerConfigOptions.TryGetValue(editorConfigStorageLocation.KeyName, out var stringValue) && editorConfigStorageLocation.TryGetOption(stringValue, typeof(T), out value)) { return true; } if (storageLocation is not IEditorConfigStorageLocation configStorageLocation) { continue; } // This option has .editorconfig storage defined, even if the current configuration does not provide a // value for it. hasEditorConfigStorage = true; if (configStorageLocation.TryGetOption(analyzerConfigOptions, option.Type, out var objectValue)) { value = (T)objectValue; return true; } } if (useDefaultIfMissing) { value = (T?)option.DefaultValue; return hasEditorConfigStorage; } else { value = default; return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; #if CODE_STYLE using TOption = Microsoft.CodeAnalysis.Options.IOption2; #else using TOption = Microsoft.CodeAnalysis.Options.IOption; #endif namespace Microsoft.CodeAnalysis { internal static class AnalyzerConfigOptionsExtensions { #if CODE_STYLE public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption2<T> option, string language) { // Language is not used for .editorconfig lookups _ = language; return GetOption(analyzerConfigOptions, option); } #else public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, Options.Option<T> option) => GetOptionWithAssertOnFailure<T>(analyzerConfigOptions, option); public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, Options.PerLanguageOption<T> option) => GetOptionWithAssertOnFailure<T>(analyzerConfigOptions, option); #endif public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, Option2<T> option) => GetOptionWithAssertOnFailure<T>(analyzerConfigOptions, option); public static T GetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption2<T> option) => GetOptionWithAssertOnFailure<T>(analyzerConfigOptions, option); private static T GetOptionWithAssertOnFailure<T>(AnalyzerConfigOptions analyzerConfigOptions, TOption option) { if (!TryGetEditorConfigOptionOrDefault(analyzerConfigOptions, option, out T value)) { // There are couple of reasons this assert might fire: // 1. Attempting to access an option which does not have an IEditorConfigStorageLocation. // 2. Attempting to access an option which is not exposed from any option provider, i.e. IOptionProvider.Options. Debug.Fail("Failed to find a .editorconfig key for the option."); value = (T)option.DefaultValue!; } return value; } public static bool TryGetEditorConfigOptionOrDefault<T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, out T value) => TryGetEditorConfigOption(analyzerConfigOptions, option, useDefaultIfMissing: true, out value!); public static bool TryGetEditorConfigOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, [MaybeNullWhen(false)] out T value) => TryGetEditorConfigOption(analyzerConfigOptions, option, useDefaultIfMissing: false, out value); private static bool TryGetEditorConfigOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, bool useDefaultIfMissing, out T? value) { var hasEditorConfigStorage = false; foreach (var storageLocation in option.StorageLocations) { // This code path will avoid allocating a Dictionary wrapper since we can get direct access to the KeyName. if (storageLocation is EditorConfigStorageLocation<T> editorConfigStorageLocation && analyzerConfigOptions.TryGetValue(editorConfigStorageLocation.KeyName, out var stringValue) && editorConfigStorageLocation.TryGetOption(stringValue, typeof(T), out value)) { return true; } if (storageLocation is not IEditorConfigStorageLocation configStorageLocation) { continue; } // This option has .editorconfig storage defined, even if the current configuration does not provide a // value for it. hasEditorConfigStorage = true; if (configStorageLocation.TryGetOption(analyzerConfigOptions, option.Type, out var objectValue)) { value = (T)objectValue; return true; } } if (useDefaultIfMissing) { value = (T?)option.DefaultValue; return hasEditorConfigStorage; } else { value = default; return false; } } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/VisualStudio/Core/Impl/Options/Converters/NullableBoolOptionConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Converters { internal class NullableBoolOptionConverter : IValueConverter { private readonly Func<bool> _onNullValue; public NullableBoolOptionConverter(Func<bool> onNullValue) { _onNullValue = onNullValue; } public object Convert(object? value, Type targetType, object parameter, CultureInfo culture) => value switch { null => _onNullValue(), bool b => b, _ => DependencyProperty.UnsetValue }; public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => 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; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Converters { internal class NullableBoolOptionConverter : IValueConverter { private readonly Func<bool> _onNullValue; public NullableBoolOptionConverter(Func<bool> onNullValue) { _onNullValue = onNullValue; } public object Convert(object? value, Type targetType, object parameter, CultureInfo culture) => value switch { null => _onNullValue(), bool b => b, _ => DependencyProperty.UnsetValue }; public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => value; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/ShouldUnsetParentConfigurationAndPlatform.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 ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Condition="$(ShouldUnsetParentConfigurationAndPlatform)" Include="ShouldUnsetParentConfigurationAndPlatformConditional.cs" /> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </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 ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Condition="$(ShouldUnsetParentConfigurationAndPlatform)" Include="ShouldUnsetParentConfigurationAndPlatformConditional.cs" /> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/Core/Portable/Rename/TokenRenameInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Rename { internal sealed class TokenRenameInfo { public bool HasSymbols { get; private set; } public IEnumerable<ISymbol> Symbols { get; private set; } public bool IsMemberGroup { get; private set; } public static TokenRenameInfo CreateMemberGroupTokenInfo(IEnumerable<ISymbol> symbols) { return new TokenRenameInfo { HasSymbols = true, IsMemberGroup = true, Symbols = symbols }; } public static TokenRenameInfo CreateSingleSymbolTokenInfo(ISymbol symbol) { return new TokenRenameInfo { HasSymbols = true, IsMemberGroup = false, Symbols = SpecializedCollections.SingletonEnumerable(symbol) }; } public static TokenRenameInfo NoSymbolsTokenInfo = new() { HasSymbols = false, IsMemberGroup = false, Symbols = SpecializedCollections.EmptyEnumerable<ISymbol>() }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Rename { internal sealed class TokenRenameInfo { public bool HasSymbols { get; private set; } public IEnumerable<ISymbol> Symbols { get; private set; } public bool IsMemberGroup { get; private set; } public static TokenRenameInfo CreateMemberGroupTokenInfo(IEnumerable<ISymbol> symbols) { return new TokenRenameInfo { HasSymbols = true, IsMemberGroup = true, Symbols = symbols }; } public static TokenRenameInfo CreateSingleSymbolTokenInfo(ISymbol symbol) { return new TokenRenameInfo { HasSymbols = true, IsMemberGroup = false, Symbols = SpecializedCollections.SingletonEnumerable(symbol) }; } public static TokenRenameInfo NoSymbolsTokenInfo = new() { HasSymbols = false, IsMemberGroup = false, Symbols = SpecializedCollections.EmptyEnumerable<ISymbol>() }; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/Library/VsNavInfo/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo { internal static class Extensions { public static void Add(this ImmutableArray<NavInfoNode>.Builder builder, string name, _LIB_LISTTYPE type, bool expandDottedNames) { if (name == null) { return; } if (expandDottedNames) { const char separator = '.'; var start = 0; var separatorPos = name.IndexOf(separator, start); while (separatorPos >= 0) { builder.Add(name.Substring(start, separatorPos - start), type); start = separatorPos + 1; separatorPos = name.IndexOf(separator, start); } if (start < name.Length) { builder.Add(name.Substring(start), type); } } else { builder.Add(name, type); } } public static void Add(this ImmutableArray<NavInfoNode>.Builder builder, string name, _LIB_LISTTYPE type) { if (string.IsNullOrEmpty(name)) { return; } builder.Add(new NavInfoNode(name, type)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo { internal static class Extensions { public static void Add(this ImmutableArray<NavInfoNode>.Builder builder, string name, _LIB_LISTTYPE type, bool expandDottedNames) { if (name == null) { return; } if (expandDottedNames) { const char separator = '.'; var start = 0; var separatorPos = name.IndexOf(separator, start); while (separatorPos >= 0) { builder.Add(name.Substring(start, separatorPos - start), type); start = separatorPos + 1; separatorPos = name.IndexOf(separator, start); } if (start < name.Length) { builder.Add(name.Substring(start), type); } } else { builder.Add(name, type); } } public static void Add(this ImmutableArray<NavInfoNode>.Builder builder, string name, _LIB_LISTTYPE type) { if (string.IsNullOrEmpty(name)) { return; } builder.Add(new NavInfoNode(name, type)); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/EditorFeatures/VisualBasicTest/ConflictMarkerResolution/ConflictMarkerResolutionTests.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.ConflictMarkerResolution Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.VisualBasic.ConflictMarkerResolution.VisualBasicResolveConflictMarkerCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConflictMarkerResolution Public Class ConflictMarkerResolutionTests <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeTop1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 0, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeBottom1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 1, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeBoth1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 2, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program end class class Program3 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 0, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll2() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program2 end class class Program4 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 1, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll3() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program end class class Program2 end class class Program3 end class class Program4 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 2, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey }.RunAsync() End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.ConflictMarkerResolution Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.VisualBasic.ConflictMarkerResolution.VisualBasicResolveConflictMarkerCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConflictMarkerResolution Public Class ConflictMarkerResolutionTests <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeTop1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 0, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeBottom1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 1, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeBoth1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 2, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program end class class Program3 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 0, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll2() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program2 end class class Program4 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 1, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll3() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program end class class Program2 end class class Program3 end class class Program4 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 2, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey }.RunAsync() End Function End Class End Namespace
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/DelegateTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTests : CSharpTestBase { [Fact] public void MissingTypes() { var text = @" delegate void A(); "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // (2,15): error CS0518: Predefined type 'System.MulticastDelegate' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.MulticastDelegate"), // (2,10): error CS0518: Predefined type 'System.Void' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void"), // (2,1): error CS0518: Predefined type 'System.Void' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.Void"), // (2,1): error CS0518: Predefined type 'System.Object' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.Object"), // (2,1): error CS0518: Predefined type 'System.IntPtr' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.IntPtr") ); } [WorkItem(530363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530363")] [Fact] public void MissingAsyncTypes() { var source = "delegate void A();"; var comp = CreateEmptyCompilation( source: new[] { Parse(source) }, references: new[] { MinCorlibRef }); comp.VerifyDiagnostics(); } [Fact] public void Simple1() { var text = @" class A { delegate void D(); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var d = a.GetMembers("D")[0] as NamedTypeSymbol; var tmp = d.GetMembers(); Assert.Equal(d.Locations[0], d.DelegateInvokeMethod.Locations[0], EqualityComparer<Location>.Default); Assert.Equal(d.Locations[0], d.InstanceConstructors[0].Locations[0], EqualityComparer<Location>.Default); } [Fact] public void Duplicate() { var text = @" delegate void D(int x); delegate void D(float y); "; var comp = CreateCompilation(text); var diags = comp.GetDeclarationDiagnostics(); Assert.Equal(1, diags.Count()); var global = comp.GlobalNamespace; var d = global.GetTypeMembers("D", 0); Assert.Equal(2, d.Length); } [Fact] public void MetadataDelegateField() { var text = @" class A { public System.Func<int> Field; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var field = a.GetMembers("Field")[0] as FieldSymbol; var fieldType = field.Type as NamedTypeSymbol; Assert.Equal(TypeKind.Delegate, fieldType.TypeKind); var invoke = fieldType.DelegateInvokeMethod; Assert.Equal(MethodKind.DelegateInvoke, invoke.MethodKind); var ctor = fieldType.InstanceConstructors[0]; Assert.Equal(2, ctor.Parameters.Length); Assert.Equal(comp.GetSpecialType(SpecialType.System_Object), ctor.Parameters[0].Type); Assert.Equal(comp.GetSpecialType(SpecialType.System_IntPtr), ctor.Parameters[1].Type); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [Fact] public void SimpleDelegate() { var text = @"delegate void MyDel(int n);"; var comp = CreateCompilation(text); var v = comp.GlobalNamespace.GetTypeMembers("MyDel", 0).Single(); Assert.NotNull(v); Assert.Equal(SymbolKind.NamedType, v.Kind); Assert.Equal(TypeKind.Delegate, v.TypeKind); Assert.True(v.IsReferenceType); Assert.False(v.IsValueType); Assert.True(v.IsSealed); Assert.False(v.IsAbstract); Assert.Equal(0, v.Arity); // number of type parameters Assert.Equal(1, v.DelegateInvokeMethod.Parameters.Length); Assert.Equal(Accessibility.Internal, v.DeclaredAccessibility); Assert.Equal("System.MulticastDelegate", v.BaseType().ToTestDisplayString()); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [WorkItem(538707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538707")] [Fact] public void BeginInvokeEndInvoke() { var text = @" delegate int MyDel(int x, ref int y, out int z); namespace System { interface IAsyncResult {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var myDel = global.GetTypeMembers("MyDel", 0).Single() as NamedTypeSymbol; var invoke = myDel.DelegateInvokeMethod; var beginInvoke = myDel.GetMembers("BeginInvoke").Single() as MethodSymbol; Assert.Equal(invoke.Parameters.Length + 2, beginInvoke.Parameters.Length); Assert.Equal(TypeKind.Interface, beginInvoke.ReturnType.TypeKind); Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.ToTestDisplayString()); for (int i = 0; i < invoke.Parameters.Length; i++) { Assert.Equal(invoke.Parameters[i].Type, beginInvoke.Parameters[i].Type); Assert.Equal(invoke.Parameters[i].RefKind, beginInvoke.Parameters[i].RefKind); } var lastParameterType = beginInvoke.Parameters[invoke.Parameters.Length].Type; Assert.Equal("System.AsyncCallback", lastParameterType.ToTestDisplayString()); Assert.Equal(SpecialType.System_AsyncCallback, lastParameterType.SpecialType); Assert.Equal("System.Object", beginInvoke.Parameters[invoke.Parameters.Length + 1].Type.ToTestDisplayString()); var endInvoke = myDel.GetMembers("EndInvoke").Single() as MethodSymbol; Assert.Equal(invoke.ReturnType, endInvoke.ReturnType); int k = 0; for (int i = 0; i < invoke.Parameters.Length; i++) { if (invoke.Parameters[i].RefKind != RefKind.None) { Assert.Equal(invoke.Parameters[i].Type, endInvoke.Parameters[k].Type); Assert.Equal(invoke.Parameters[i].RefKind, endInvoke.Parameters[k++].RefKind); } } lastParameterType = endInvoke.Parameters[k++].Type; Assert.Equal("System.IAsyncResult", lastParameterType.ToTestDisplayString()); Assert.Equal(SpecialType.System_IAsyncResult, lastParameterType.SpecialType); Assert.Equal(k, endInvoke.Parameters.Length); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [Fact] public void GenericDelegate() { var text = @"namespace NS { internal delegate void D<Q>(Q q); }"; var comp = CreateCompilation(text); var namespaceNS = comp.GlobalNamespace.GetMembers("NS").First() as NamespaceOrTypeSymbol; Assert.Equal(1, namespaceNS.GetTypeMembers().Length); var d = namespaceNS.GetTypeMembers("D").First(); Assert.Equal(namespaceNS, d.ContainingSymbol); Assert.Equal(SymbolKind.NamedType, d.Kind); Assert.Equal(TypeKind.Delegate, d.TypeKind); Assert.Equal(Accessibility.Internal, d.DeclaredAccessibility); Assert.Equal(1, d.TypeParameters.Length); Assert.Equal("Q", d.TypeParameters[0].Name); var q = d.TypeParameters[0]; Assert.Equal(q.ContainingSymbol, d); Assert.Equal(d.DelegateInvokeMethod.Parameters[0].Type, q); // same as type parameter Assert.Equal(1, d.TypeArguments().Length); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void DelegateEscapedIdentifier() { var text = @" delegate void @out(); "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol dout = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("out").Single(); Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); } [Fact] public void DelegatesEverywhere() { var text = @" using System; delegate int Intf(int x); class C { Intf I; Intf Method(Intf f1) { Intf i = f1; i = f1; I = i; i = I; Delegate d1 = f1; MulticastDelegate m1 = f1; object o1 = f1; f1 = i; return f1; } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void DelegateCreation() { var text = @" namespace CSSample { class Program { static void Main(string[] args) { } delegate void D1(); delegate void D2(); delegate int D3(int x); static D1 d1; static D2 d2; static D3 d3; internal virtual void V() { } void M() { } static void S() { } static int M2(int x) { return x; } static void F(Program p) { // Good cases d2 = new D2(d1); d1 = new D1(d2); d1 = new D1(d2.Invoke); d1 = new D1(d1); d1 = new D1(p.V); d1 = new D1(p.M); d1 = new D1(S); } } } "; CreateCompilation(text).VerifyDiagnostics( // (17,19): warning CS0169: The field 'CSSample.Program.d3' is never used // static D3 d3; Diagnostic(ErrorCode.WRN_UnreferencedField, "d3").WithArguments("CSSample.Program.d3")); } [WorkItem(538722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538722")] [Fact] public void MulticastIsNotDelegate() { var text = @" using System; class Program { static void Main() { MulticastDelegate d = Main; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (7,27): error CS0428: Cannot convert method group 'Main' to non-delegate type 'System.MulticastDelegate'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate")); CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(538706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538706")] [Fact] public void DelegateMethodParameterNames() { var text = @" delegate int D(int x, ref int y, out int z); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(3, invokeParameters.Length); Assert.Equal("x", invokeParameters[0].Name); Assert.Equal("y", invokeParameters[1].Name); Assert.Equal("z", invokeParameters[2].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(5, beginInvokeParameters.Length); Assert.Equal("x", beginInvokeParameters[0].Name); Assert.Equal("y", beginInvokeParameters[1].Name); Assert.Equal("z", beginInvokeParameters[2].Name); Assert.Equal("callback", beginInvokeParameters[3].Name); Assert.Equal("object", beginInvokeParameters[4].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(3, endInvokeParameters.Length); Assert.Equal("y", endInvokeParameters[0].Name); Assert.Equal("z", endInvokeParameters[1].Name); Assert.Equal("result", endInvokeParameters[2].Name); } [WorkItem(541179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541179")] [Fact] public void DelegateWithTypeParameterNamedInvoke() { var text = @" delegate void F<Invoke>(Invoke i); class Goo { void M(int i) { F<int> x = M; } } "; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult() { var text = @" delegate void D(out int result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(1, invokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(3, beginInvokeParameters.Length); Assert.Equal("result", beginInvokeParameters[0].Name); Assert.Equal("callback", beginInvokeParameters[1].Name); Assert.Equal("object", beginInvokeParameters[2].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(2, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); Assert.Equal("__result", endInvokeParameters[1].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult2() { var text = @" delegate void D(out int @__result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(1, invokeParameters.Length); Assert.Equal("__result", invokeParameters[0].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(3, beginInvokeParameters.Length); Assert.Equal("__result", beginInvokeParameters[0].Name); Assert.Equal("callback", beginInvokeParameters[1].Name); Assert.Equal("object", beginInvokeParameters[2].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(2, endInvokeParameters.Length); Assert.Equal("__result", endInvokeParameters[0].Name); Assert.Equal("result", endInvokeParameters[1].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult3() { var text = @" delegate void D(out int result, out int @__result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(2, invokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); Assert.Equal("__result", invokeParameters[1].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(4, beginInvokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); Assert.Equal("__result", invokeParameters[1].Name); Assert.Equal("callback", beginInvokeParameters[2].Name); Assert.Equal("object", beginInvokeParameters[3].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(3, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); Assert.Equal("__result", endInvokeParameters[1].Name); Assert.Equal("____result", endInvokeParameters[2].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithParametersNamedCallbackAndObject() { var text = @" delegate void D(int callback, int @object); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(2, invokeParameters.Length); Assert.Equal("callback", invokeParameters[0].Name); Assert.Equal("object", invokeParameters[1].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(4, beginInvokeParameters.Length); Assert.Equal("callback", beginInvokeParameters[0].Name); Assert.Equal("object", beginInvokeParameters[1].Name); Assert.Equal("__callback", beginInvokeParameters[2].Name); Assert.Equal("__object", beginInvokeParameters[3].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(1, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); } [Fact] public void DelegateConversion() { var text = @" public class A { } public class B { } public class C<T> { } public class DelegateTest { public static void FT<T>(T t) { } public static void FTT<T>(T t1, T t2) { } public static void FTi<T>(T t, int x) { } public static void FST<S, T>(S s, T t) { } public static void FCT<T>(C<T> c) { } public static void PT<T>(params T[] args) { } public static void PTT<T>(T t, params T[] arr) { } public static void PST<S, T>(S s, params T[] arr) { } public delegate void Da(A x); public delegate void Daa(A x, A y); public delegate void Dab(A x, B y); public delegate void Dai(A x, int y); public delegate void Dpa(A[] x); public delegate void Dapa(A x, A[] y); public delegate void Dapb(A x, B[] y); public delegate void Dpapa(A[] x, A[] y); public delegate void Dca(C<A> x); public delegate void D1<T>(T t); public static void Run() { Da da; Daa daa; Dai dai; Dab dab; Dpa dpa; Dapa dapa; Dapb dapb; Dpapa dpapa; Dca dca; da = new Da(FTT); da = new Da(FCT); da = new Da(PT); daa = new Daa(FT); daa = new Daa(FTi); daa = new Daa(PTT); daa = new Daa(PST); dai = new Dai(FT); dai = new Dai(FTT); dai = new Dai(PTT); dai = new Dai(PST); dab = new Dab(FT); dab = new Dab(FTT); dab = new Dab(FTi); dab = new Dab(PTT); dab = new Dab(PST); dpa = new Dpa(FTT); dpa = new Dpa(FCT); dapa = new Dapa(FT); dapa = new Dapa(FTT); dapb = new Dapb(FT); dapb = new Dapb(FTT); dapb = new Dapb(PTT); dpapa = new Dpapa(FT); dpapa = new Dpapa(PTT); dca = new Dca(FTT); dca = new Dca(PT); RunG(null); } public static void RunG<T>(T t) { } } "; CreateCompilation(text).VerifyDiagnostics( // (44,14): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Da' // da = new Da(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Da(FTT)").WithArguments("FTT", "DelegateTest.Da").WithLocation(44, 14), // (45,21): error CS0411: The type arguments for method 'DelegateTest.FCT<T>(C<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // da = new Da(FCT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FCT").WithArguments("DelegateTest.FCT<T>(C<T>)").WithLocation(45, 21), // (46,21): error CS0411: The type arguments for method 'DelegateTest.PT<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // da = new Da(PT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PT").WithArguments("DelegateTest.PT<T>(params T[])").WithLocation(46, 21), // (48,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Daa' // daa = new Daa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(FT)").WithArguments("FT", "DelegateTest.Daa").WithLocation(48, 15), // (49,15): error CS0123: No overload for 'FTi' matches delegate 'DelegateTest.Daa' // daa = new Daa(FTi); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(FTi)").WithArguments("FTi", "DelegateTest.Daa").WithLocation(49, 15), // (50,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Daa' // daa = new Daa(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(PTT)").WithArguments("PTT", "DelegateTest.Daa").WithLocation(50, 15), // (51,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // daa = new Daa(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(51, 23), // (53,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dai' // dai = new Dai(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dai(FT)").WithArguments("FT", "DelegateTest.Dai").WithLocation(53, 15), // (54,23): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dai = new Dai(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(54, 23), // (55,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Dai' // dai = new Dai(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dai(PTT)").WithArguments("PTT", "DelegateTest.Dai").WithLocation(55, 15), // (56,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dai = new Dai(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(56, 23), // (58,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dab' // dab = new Dab(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(FT)").WithArguments("FT", "DelegateTest.Dab").WithLocation(58, 15), // (59,23): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dab = new Dab(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(59, 23), // (60,15): error CS0123: No overload for 'FTi' matches delegate 'DelegateTest.Dab' // dab = new Dab(FTi); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(FTi)").WithArguments("FTi", "DelegateTest.Dab").WithLocation(60, 15), // (61,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Dab' // dab = new Dab(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(PTT)").WithArguments("PTT", "DelegateTest.Dab").WithLocation(61, 15), // (62,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dab = new Dab(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(62, 23), // (64,15): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Dpa' // dpa = new Dpa(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dpa(FTT)").WithArguments("FTT", "DelegateTest.Dpa").WithLocation(64, 15), // (65,23): error CS0411: The type arguments for method 'DelegateTest.FCT<T>(C<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dpa = new Dpa(FCT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FCT").WithArguments("DelegateTest.FCT<T>(C<T>)").WithLocation(65, 23), // (67,16): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dapa' // dapa = new Dapa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dapa(FT)").WithArguments("FT", "DelegateTest.Dapa").WithLocation(67, 16), // (68,25): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapa = new Dapa(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(68, 25), // (70,16): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dapb' // dapb = new Dapb(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dapb(FT)").WithArguments("FT", "DelegateTest.Dapb").WithLocation(70, 16), // (71,25): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapb = new Dapb(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(71, 25), // (72,25): error CS0411: The type arguments for method 'DelegateTest.PTT<T>(T, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapb = new Dapb(PTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PTT").WithArguments("DelegateTest.PTT<T>(T, params T[])").WithLocation(72, 25), // (74,17): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dpapa' // dpapa = new Dpapa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dpapa(FT)").WithArguments("FT", "DelegateTest.Dpapa").WithLocation(74, 17), // (75,27): error CS0411: The type arguments for method 'DelegateTest.PTT<T>(T, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dpapa = new Dpapa(PTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PTT").WithArguments("DelegateTest.PTT<T>(T, params T[])").WithLocation(75, 27), // (77,15): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Dca' // dca = new Dca(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dca(FTT)").WithArguments("FTT", "DelegateTest.Dca").WithLocation(77, 15), // (78,23): error CS0411: The type arguments for method 'DelegateTest.PT<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dca = new Dca(PT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PT").WithArguments("DelegateTest.PT<T>(params T[])").WithLocation(78, 23), // (80,9): error CS0411: The type arguments for method 'DelegateTest.RunG<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // RunG(null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "RunG").WithArguments("DelegateTest.RunG<T>(T)").WithLocation(80, 9)); } [Fact] public void CastFromMulticastDelegate() { var source = @"using System; delegate void D(); class Program { public static void Main(string[] args) { MulticastDelegate d = null; D d2 = (D)d; } } "; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(634014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634014")] [Fact] public void DelegateTest634014() { var source = @"delegate void D(ref int x); class C { D d = async delegate { }; }"; CreateCompilation(source).VerifyDiagnostics( // (4,17): error CS1988: Async methods cannot have ref, in or out parameters // D d = async delegate { }; Diagnostic(ErrorCode.ERR_BadAsyncArgType, "delegate"), // (4,17): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // D d = async delegate { }; Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "delegate").WithLocation(4, 17)); } [Fact] public void RefReturningDelegate() { var source = @"delegate ref int D();"; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var d = global.GetMembers("D")[0] as NamedTypeSymbol; Assert.True(d.DelegateInvokeMethod.ReturnsByRef); Assert.False(d.DelegateInvokeMethod.ReturnsByRefReadonly); Assert.Equal(RefKind.Ref, d.DelegateInvokeMethod.RefKind); Assert.Equal(RefKind.Ref, ((MethodSymbol)d.GetMembers("EndInvoke").Single()).RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningDelegate() { var source = @"delegate ref readonly int D(in int arg);"; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var d = global.GetMembers("D")[0] as NamedTypeSymbol; Assert.False(d.DelegateInvokeMethod.ReturnsByRef); Assert.True(d.DelegateInvokeMethod.ReturnsByRefReadonly); Assert.Equal(RefKind.RefReadOnly, d.DelegateInvokeMethod.RefKind); Assert.Equal(RefKind.RefReadOnly, ((MethodSymbol)d.GetMembers("EndInvoke").Single()).RefKind); Assert.Equal(RefKind.In, d.DelegateInvokeMethod.Parameters[0].RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlysInlambda() { var source = @" class C { public delegate ref readonly T DD<T>(in T arg); public static void Main() { DD<int> d1 = (in int a) => ref a; DD<int> d2 = delegate(in int a){return ref a;}; } }"; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular); var compilation = CreateCompilationWithMscorlib45(new SyntaxTree[] { tree }).VerifyDiagnostics(); var model = compilation.GetSemanticModel(tree); ExpressionSyntax lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var lambda = (IMethodSymbol)model.GetSymbolInfo(lambdaSyntax).Symbol; Assert.False(lambda.ReturnsByRef); Assert.True(lambda.ReturnsByRefReadonly); Assert.Equal(RefKind.In, lambda.Parameters[0].RefKind); lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); lambda = (IMethodSymbol)model.GetSymbolInfo(lambdaSyntax).Symbol; Assert.False(lambda.ReturnsByRef); Assert.True(lambda.ReturnsByRefReadonly); Assert.Equal(RefKind.In, lambda.Parameters[0].RefKind); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTests : CSharpTestBase { [Fact] public void MissingTypes() { var text = @" delegate void A(); "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // (2,15): error CS0518: Predefined type 'System.MulticastDelegate' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.MulticastDelegate"), // (2,10): error CS0518: Predefined type 'System.Void' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void"), // (2,1): error CS0518: Predefined type 'System.Void' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.Void"), // (2,1): error CS0518: Predefined type 'System.Object' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.Object"), // (2,1): error CS0518: Predefined type 'System.IntPtr' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.IntPtr") ); } [WorkItem(530363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530363")] [Fact] public void MissingAsyncTypes() { var source = "delegate void A();"; var comp = CreateEmptyCompilation( source: new[] { Parse(source) }, references: new[] { MinCorlibRef }); comp.VerifyDiagnostics(); } [Fact] public void Simple1() { var text = @" class A { delegate void D(); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var d = a.GetMembers("D")[0] as NamedTypeSymbol; var tmp = d.GetMembers(); Assert.Equal(d.Locations[0], d.DelegateInvokeMethod.Locations[0], EqualityComparer<Location>.Default); Assert.Equal(d.Locations[0], d.InstanceConstructors[0].Locations[0], EqualityComparer<Location>.Default); } [Fact] public void Duplicate() { var text = @" delegate void D(int x); delegate void D(float y); "; var comp = CreateCompilation(text); var diags = comp.GetDeclarationDiagnostics(); Assert.Equal(1, diags.Count()); var global = comp.GlobalNamespace; var d = global.GetTypeMembers("D", 0); Assert.Equal(2, d.Length); } [Fact] public void MetadataDelegateField() { var text = @" class A { public System.Func<int> Field; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var field = a.GetMembers("Field")[0] as FieldSymbol; var fieldType = field.Type as NamedTypeSymbol; Assert.Equal(TypeKind.Delegate, fieldType.TypeKind); var invoke = fieldType.DelegateInvokeMethod; Assert.Equal(MethodKind.DelegateInvoke, invoke.MethodKind); var ctor = fieldType.InstanceConstructors[0]; Assert.Equal(2, ctor.Parameters.Length); Assert.Equal(comp.GetSpecialType(SpecialType.System_Object), ctor.Parameters[0].Type); Assert.Equal(comp.GetSpecialType(SpecialType.System_IntPtr), ctor.Parameters[1].Type); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [Fact] public void SimpleDelegate() { var text = @"delegate void MyDel(int n);"; var comp = CreateCompilation(text); var v = comp.GlobalNamespace.GetTypeMembers("MyDel", 0).Single(); Assert.NotNull(v); Assert.Equal(SymbolKind.NamedType, v.Kind); Assert.Equal(TypeKind.Delegate, v.TypeKind); Assert.True(v.IsReferenceType); Assert.False(v.IsValueType); Assert.True(v.IsSealed); Assert.False(v.IsAbstract); Assert.Equal(0, v.Arity); // number of type parameters Assert.Equal(1, v.DelegateInvokeMethod.Parameters.Length); Assert.Equal(Accessibility.Internal, v.DeclaredAccessibility); Assert.Equal("System.MulticastDelegate", v.BaseType().ToTestDisplayString()); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [WorkItem(538707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538707")] [Fact] public void BeginInvokeEndInvoke() { var text = @" delegate int MyDel(int x, ref int y, out int z); namespace System { interface IAsyncResult {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var myDel = global.GetTypeMembers("MyDel", 0).Single() as NamedTypeSymbol; var invoke = myDel.DelegateInvokeMethod; var beginInvoke = myDel.GetMembers("BeginInvoke").Single() as MethodSymbol; Assert.Equal(invoke.Parameters.Length + 2, beginInvoke.Parameters.Length); Assert.Equal(TypeKind.Interface, beginInvoke.ReturnType.TypeKind); Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.ToTestDisplayString()); for (int i = 0; i < invoke.Parameters.Length; i++) { Assert.Equal(invoke.Parameters[i].Type, beginInvoke.Parameters[i].Type); Assert.Equal(invoke.Parameters[i].RefKind, beginInvoke.Parameters[i].RefKind); } var lastParameterType = beginInvoke.Parameters[invoke.Parameters.Length].Type; Assert.Equal("System.AsyncCallback", lastParameterType.ToTestDisplayString()); Assert.Equal(SpecialType.System_AsyncCallback, lastParameterType.SpecialType); Assert.Equal("System.Object", beginInvoke.Parameters[invoke.Parameters.Length + 1].Type.ToTestDisplayString()); var endInvoke = myDel.GetMembers("EndInvoke").Single() as MethodSymbol; Assert.Equal(invoke.ReturnType, endInvoke.ReturnType); int k = 0; for (int i = 0; i < invoke.Parameters.Length; i++) { if (invoke.Parameters[i].RefKind != RefKind.None) { Assert.Equal(invoke.Parameters[i].Type, endInvoke.Parameters[k].Type); Assert.Equal(invoke.Parameters[i].RefKind, endInvoke.Parameters[k++].RefKind); } } lastParameterType = endInvoke.Parameters[k++].Type; Assert.Equal("System.IAsyncResult", lastParameterType.ToTestDisplayString()); Assert.Equal(SpecialType.System_IAsyncResult, lastParameterType.SpecialType); Assert.Equal(k, endInvoke.Parameters.Length); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [Fact] public void GenericDelegate() { var text = @"namespace NS { internal delegate void D<Q>(Q q); }"; var comp = CreateCompilation(text); var namespaceNS = comp.GlobalNamespace.GetMembers("NS").First() as NamespaceOrTypeSymbol; Assert.Equal(1, namespaceNS.GetTypeMembers().Length); var d = namespaceNS.GetTypeMembers("D").First(); Assert.Equal(namespaceNS, d.ContainingSymbol); Assert.Equal(SymbolKind.NamedType, d.Kind); Assert.Equal(TypeKind.Delegate, d.TypeKind); Assert.Equal(Accessibility.Internal, d.DeclaredAccessibility); Assert.Equal(1, d.TypeParameters.Length); Assert.Equal("Q", d.TypeParameters[0].Name); var q = d.TypeParameters[0]; Assert.Equal(q.ContainingSymbol, d); Assert.Equal(d.DelegateInvokeMethod.Parameters[0].Type, q); // same as type parameter Assert.Equal(1, d.TypeArguments().Length); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void DelegateEscapedIdentifier() { var text = @" delegate void @out(); "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol dout = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("out").Single(); Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); } [Fact] public void DelegatesEverywhere() { var text = @" using System; delegate int Intf(int x); class C { Intf I; Intf Method(Intf f1) { Intf i = f1; i = f1; I = i; i = I; Delegate d1 = f1; MulticastDelegate m1 = f1; object o1 = f1; f1 = i; return f1; } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void DelegateCreation() { var text = @" namespace CSSample { class Program { static void Main(string[] args) { } delegate void D1(); delegate void D2(); delegate int D3(int x); static D1 d1; static D2 d2; static D3 d3; internal virtual void V() { } void M() { } static void S() { } static int M2(int x) { return x; } static void F(Program p) { // Good cases d2 = new D2(d1); d1 = new D1(d2); d1 = new D1(d2.Invoke); d1 = new D1(d1); d1 = new D1(p.V); d1 = new D1(p.M); d1 = new D1(S); } } } "; CreateCompilation(text).VerifyDiagnostics( // (17,19): warning CS0169: The field 'CSSample.Program.d3' is never used // static D3 d3; Diagnostic(ErrorCode.WRN_UnreferencedField, "d3").WithArguments("CSSample.Program.d3")); } [WorkItem(538722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538722")] [Fact] public void MulticastIsNotDelegate() { var text = @" using System; class Program { static void Main() { MulticastDelegate d = Main; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (7,27): error CS0428: Cannot convert method group 'Main' to non-delegate type 'System.MulticastDelegate'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate")); CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(538706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538706")] [Fact] public void DelegateMethodParameterNames() { var text = @" delegate int D(int x, ref int y, out int z); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(3, invokeParameters.Length); Assert.Equal("x", invokeParameters[0].Name); Assert.Equal("y", invokeParameters[1].Name); Assert.Equal("z", invokeParameters[2].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(5, beginInvokeParameters.Length); Assert.Equal("x", beginInvokeParameters[0].Name); Assert.Equal("y", beginInvokeParameters[1].Name); Assert.Equal("z", beginInvokeParameters[2].Name); Assert.Equal("callback", beginInvokeParameters[3].Name); Assert.Equal("object", beginInvokeParameters[4].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(3, endInvokeParameters.Length); Assert.Equal("y", endInvokeParameters[0].Name); Assert.Equal("z", endInvokeParameters[1].Name); Assert.Equal("result", endInvokeParameters[2].Name); } [WorkItem(541179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541179")] [Fact] public void DelegateWithTypeParameterNamedInvoke() { var text = @" delegate void F<Invoke>(Invoke i); class Goo { void M(int i) { F<int> x = M; } } "; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult() { var text = @" delegate void D(out int result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(1, invokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(3, beginInvokeParameters.Length); Assert.Equal("result", beginInvokeParameters[0].Name); Assert.Equal("callback", beginInvokeParameters[1].Name); Assert.Equal("object", beginInvokeParameters[2].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(2, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); Assert.Equal("__result", endInvokeParameters[1].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult2() { var text = @" delegate void D(out int @__result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(1, invokeParameters.Length); Assert.Equal("__result", invokeParameters[0].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(3, beginInvokeParameters.Length); Assert.Equal("__result", beginInvokeParameters[0].Name); Assert.Equal("callback", beginInvokeParameters[1].Name); Assert.Equal("object", beginInvokeParameters[2].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(2, endInvokeParameters.Length); Assert.Equal("__result", endInvokeParameters[0].Name); Assert.Equal("result", endInvokeParameters[1].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult3() { var text = @" delegate void D(out int result, out int @__result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(2, invokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); Assert.Equal("__result", invokeParameters[1].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(4, beginInvokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); Assert.Equal("__result", invokeParameters[1].Name); Assert.Equal("callback", beginInvokeParameters[2].Name); Assert.Equal("object", beginInvokeParameters[3].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(3, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); Assert.Equal("__result", endInvokeParameters[1].Name); Assert.Equal("____result", endInvokeParameters[2].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithParametersNamedCallbackAndObject() { var text = @" delegate void D(int callback, int @object); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(2, invokeParameters.Length); Assert.Equal("callback", invokeParameters[0].Name); Assert.Equal("object", invokeParameters[1].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(4, beginInvokeParameters.Length); Assert.Equal("callback", beginInvokeParameters[0].Name); Assert.Equal("object", beginInvokeParameters[1].Name); Assert.Equal("__callback", beginInvokeParameters[2].Name); Assert.Equal("__object", beginInvokeParameters[3].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(1, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); } [Fact] public void DelegateConversion() { var text = @" public class A { } public class B { } public class C<T> { } public class DelegateTest { public static void FT<T>(T t) { } public static void FTT<T>(T t1, T t2) { } public static void FTi<T>(T t, int x) { } public static void FST<S, T>(S s, T t) { } public static void FCT<T>(C<T> c) { } public static void PT<T>(params T[] args) { } public static void PTT<T>(T t, params T[] arr) { } public static void PST<S, T>(S s, params T[] arr) { } public delegate void Da(A x); public delegate void Daa(A x, A y); public delegate void Dab(A x, B y); public delegate void Dai(A x, int y); public delegate void Dpa(A[] x); public delegate void Dapa(A x, A[] y); public delegate void Dapb(A x, B[] y); public delegate void Dpapa(A[] x, A[] y); public delegate void Dca(C<A> x); public delegate void D1<T>(T t); public static void Run() { Da da; Daa daa; Dai dai; Dab dab; Dpa dpa; Dapa dapa; Dapb dapb; Dpapa dpapa; Dca dca; da = new Da(FTT); da = new Da(FCT); da = new Da(PT); daa = new Daa(FT); daa = new Daa(FTi); daa = new Daa(PTT); daa = new Daa(PST); dai = new Dai(FT); dai = new Dai(FTT); dai = new Dai(PTT); dai = new Dai(PST); dab = new Dab(FT); dab = new Dab(FTT); dab = new Dab(FTi); dab = new Dab(PTT); dab = new Dab(PST); dpa = new Dpa(FTT); dpa = new Dpa(FCT); dapa = new Dapa(FT); dapa = new Dapa(FTT); dapb = new Dapb(FT); dapb = new Dapb(FTT); dapb = new Dapb(PTT); dpapa = new Dpapa(FT); dpapa = new Dpapa(PTT); dca = new Dca(FTT); dca = new Dca(PT); RunG(null); } public static void RunG<T>(T t) { } } "; CreateCompilation(text).VerifyDiagnostics( // (44,14): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Da' // da = new Da(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Da(FTT)").WithArguments("FTT", "DelegateTest.Da").WithLocation(44, 14), // (45,21): error CS0411: The type arguments for method 'DelegateTest.FCT<T>(C<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // da = new Da(FCT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FCT").WithArguments("DelegateTest.FCT<T>(C<T>)").WithLocation(45, 21), // (46,21): error CS0411: The type arguments for method 'DelegateTest.PT<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // da = new Da(PT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PT").WithArguments("DelegateTest.PT<T>(params T[])").WithLocation(46, 21), // (48,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Daa' // daa = new Daa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(FT)").WithArguments("FT", "DelegateTest.Daa").WithLocation(48, 15), // (49,15): error CS0123: No overload for 'FTi' matches delegate 'DelegateTest.Daa' // daa = new Daa(FTi); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(FTi)").WithArguments("FTi", "DelegateTest.Daa").WithLocation(49, 15), // (50,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Daa' // daa = new Daa(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(PTT)").WithArguments("PTT", "DelegateTest.Daa").WithLocation(50, 15), // (51,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // daa = new Daa(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(51, 23), // (53,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dai' // dai = new Dai(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dai(FT)").WithArguments("FT", "DelegateTest.Dai").WithLocation(53, 15), // (54,23): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dai = new Dai(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(54, 23), // (55,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Dai' // dai = new Dai(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dai(PTT)").WithArguments("PTT", "DelegateTest.Dai").WithLocation(55, 15), // (56,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dai = new Dai(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(56, 23), // (58,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dab' // dab = new Dab(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(FT)").WithArguments("FT", "DelegateTest.Dab").WithLocation(58, 15), // (59,23): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dab = new Dab(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(59, 23), // (60,15): error CS0123: No overload for 'FTi' matches delegate 'DelegateTest.Dab' // dab = new Dab(FTi); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(FTi)").WithArguments("FTi", "DelegateTest.Dab").WithLocation(60, 15), // (61,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Dab' // dab = new Dab(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(PTT)").WithArguments("PTT", "DelegateTest.Dab").WithLocation(61, 15), // (62,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dab = new Dab(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(62, 23), // (64,15): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Dpa' // dpa = new Dpa(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dpa(FTT)").WithArguments("FTT", "DelegateTest.Dpa").WithLocation(64, 15), // (65,23): error CS0411: The type arguments for method 'DelegateTest.FCT<T>(C<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dpa = new Dpa(FCT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FCT").WithArguments("DelegateTest.FCT<T>(C<T>)").WithLocation(65, 23), // (67,16): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dapa' // dapa = new Dapa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dapa(FT)").WithArguments("FT", "DelegateTest.Dapa").WithLocation(67, 16), // (68,25): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapa = new Dapa(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(68, 25), // (70,16): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dapb' // dapb = new Dapb(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dapb(FT)").WithArguments("FT", "DelegateTest.Dapb").WithLocation(70, 16), // (71,25): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapb = new Dapb(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(71, 25), // (72,25): error CS0411: The type arguments for method 'DelegateTest.PTT<T>(T, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapb = new Dapb(PTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PTT").WithArguments("DelegateTest.PTT<T>(T, params T[])").WithLocation(72, 25), // (74,17): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dpapa' // dpapa = new Dpapa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dpapa(FT)").WithArguments("FT", "DelegateTest.Dpapa").WithLocation(74, 17), // (75,27): error CS0411: The type arguments for method 'DelegateTest.PTT<T>(T, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dpapa = new Dpapa(PTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PTT").WithArguments("DelegateTest.PTT<T>(T, params T[])").WithLocation(75, 27), // (77,15): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Dca' // dca = new Dca(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dca(FTT)").WithArguments("FTT", "DelegateTest.Dca").WithLocation(77, 15), // (78,23): error CS0411: The type arguments for method 'DelegateTest.PT<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dca = new Dca(PT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PT").WithArguments("DelegateTest.PT<T>(params T[])").WithLocation(78, 23), // (80,9): error CS0411: The type arguments for method 'DelegateTest.RunG<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // RunG(null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "RunG").WithArguments("DelegateTest.RunG<T>(T)").WithLocation(80, 9)); } [Fact] public void CastFromMulticastDelegate() { var source = @"using System; delegate void D(); class Program { public static void Main(string[] args) { MulticastDelegate d = null; D d2 = (D)d; } } "; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(634014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634014")] [Fact] public void DelegateTest634014() { var source = @"delegate void D(ref int x); class C { D d = async delegate { }; }"; CreateCompilation(source).VerifyDiagnostics( // (4,17): error CS1988: Async methods cannot have ref, in or out parameters // D d = async delegate { }; Diagnostic(ErrorCode.ERR_BadAsyncArgType, "delegate"), // (4,17): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // D d = async delegate { }; Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "delegate").WithLocation(4, 17)); } [Fact] public void RefReturningDelegate() { var source = @"delegate ref int D();"; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var d = global.GetMembers("D")[0] as NamedTypeSymbol; Assert.True(d.DelegateInvokeMethod.ReturnsByRef); Assert.False(d.DelegateInvokeMethod.ReturnsByRefReadonly); Assert.Equal(RefKind.Ref, d.DelegateInvokeMethod.RefKind); Assert.Equal(RefKind.Ref, ((MethodSymbol)d.GetMembers("EndInvoke").Single()).RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningDelegate() { var source = @"delegate ref readonly int D(in int arg);"; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var d = global.GetMembers("D")[0] as NamedTypeSymbol; Assert.False(d.DelegateInvokeMethod.ReturnsByRef); Assert.True(d.DelegateInvokeMethod.ReturnsByRefReadonly); Assert.Equal(RefKind.RefReadOnly, d.DelegateInvokeMethod.RefKind); Assert.Equal(RefKind.RefReadOnly, ((MethodSymbol)d.GetMembers("EndInvoke").Single()).RefKind); Assert.Equal(RefKind.In, d.DelegateInvokeMethod.Parameters[0].RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlysInlambda() { var source = @" class C { public delegate ref readonly T DD<T>(in T arg); public static void Main() { DD<int> d1 = (in int a) => ref a; DD<int> d2 = delegate(in int a){return ref a;}; } }"; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular); var compilation = CreateCompilationWithMscorlib45(new SyntaxTree[] { tree }).VerifyDiagnostics(); var model = compilation.GetSemanticModel(tree); ExpressionSyntax lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var lambda = (IMethodSymbol)model.GetSymbolInfo(lambdaSyntax).Symbol; Assert.False(lambda.ReturnsByRef); Assert.True(lambda.ReturnsByRefReadonly); Assert.Equal(RefKind.In, lambda.Parameters[0].RefKind); lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); lambda = (IMethodSymbol)model.GetSymbolInfo(lambdaSyntax).Symbol; Assert.False(lambda.ReturnsByRef); Assert.True(lambda.ReturnsByRefReadonly); Assert.Equal(RefKind.In, lambda.Parameters[0].RefKind); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Analyzers/Core/CodeFixes/UseObjectInitializer/AbstractUseObjectInitializerCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseObjectInitializer { internal abstract class AbstractUseObjectInitializerCodeFixProvider< TSyntaxKind, TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax> : SyntaxEditorBasedCodeFixProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TAssignmentStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseObjectInitializerDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // Fix-All for this feature is somewhat complicated. As Object-Initializers // could be arbitrarily nested, we have to make sure that any edits we make // to one Object-Initializer are seen by any higher ones. In order to do this // we actually process each object-creation-node, one at a time, rewriting // the tree for each node. In order to do this effectively, we use the '.TrackNodes' // feature to keep track of all the object creation nodes as we make edits to // the tree. If we didn't do this, then we wouldn't be able to find the // second object-creation-node after we make the edit for the first one. var workspace = document.Project.Solution.Workspace; var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var originalRoot = editor.OriginalRoot; var originalObjectCreationNodes = new Stack<TObjectCreationExpressionSyntax>(); foreach (var diagnostic in diagnostics) { var objectCreation = (TObjectCreationExpressionSyntax)originalRoot.FindNode( diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); originalObjectCreationNodes.Push(objectCreation); } // We're going to be continually editing this tree. Track all the nodes we // care about so we can find them across each edit. document = document.WithSyntaxRoot(originalRoot.TrackNodes(originalObjectCreationNodes)); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); while (originalObjectCreationNodes.Count > 0) { var originalObjectCreation = originalObjectCreationNodes.Pop(); var objectCreation = currentRoot.GetCurrentNodes(originalObjectCreation).Single(); var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax>.Analyze( semanticModel, syntaxFacts, objectCreation, cancellationToken); if (matches == null || matches.Value.Length == 0) { continue; } var statement = objectCreation.FirstAncestorOrSelf<TStatementSyntax>(); Contract.ThrowIfNull(statement); var newStatement = GetNewStatement(statement, objectCreation, matches.Value) .WithAdditionalAnnotations(Formatter.Annotation); var subEditor = new SyntaxEditor(currentRoot, workspace); subEditor.ReplaceNode(statement, newStatement); foreach (var match in matches) { subEditor.RemoveNode(match.Statement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } document = document.WithSyntaxRoot(subEditor.GetChangedRoot()); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); currentRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } editor.ReplaceNode(editor.OriginalRoot, currentRoot); } protected abstract TStatementSyntax GetNewStatement( TStatementSyntax statement, TObjectCreationExpressionSyntax objectCreation, ImmutableArray<Match<TExpressionSyntax, TStatementSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax>> matches); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Object_initialization_can_be_simplified, createChangedDocument, nameof(AnalyzersResources.Object_initialization_can_be_simplified)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseObjectInitializer { internal abstract class AbstractUseObjectInitializerCodeFixProvider< TSyntaxKind, TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax> : SyntaxEditorBasedCodeFixProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TAssignmentStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseObjectInitializerDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // Fix-All for this feature is somewhat complicated. As Object-Initializers // could be arbitrarily nested, we have to make sure that any edits we make // to one Object-Initializer are seen by any higher ones. In order to do this // we actually process each object-creation-node, one at a time, rewriting // the tree for each node. In order to do this effectively, we use the '.TrackNodes' // feature to keep track of all the object creation nodes as we make edits to // the tree. If we didn't do this, then we wouldn't be able to find the // second object-creation-node after we make the edit for the first one. var workspace = document.Project.Solution.Workspace; var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var originalRoot = editor.OriginalRoot; var originalObjectCreationNodes = new Stack<TObjectCreationExpressionSyntax>(); foreach (var diagnostic in diagnostics) { var objectCreation = (TObjectCreationExpressionSyntax)originalRoot.FindNode( diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); originalObjectCreationNodes.Push(objectCreation); } // We're going to be continually editing this tree. Track all the nodes we // care about so we can find them across each edit. document = document.WithSyntaxRoot(originalRoot.TrackNodes(originalObjectCreationNodes)); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); while (originalObjectCreationNodes.Count > 0) { var originalObjectCreation = originalObjectCreationNodes.Pop(); var objectCreation = currentRoot.GetCurrentNodes(originalObjectCreation).Single(); var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax>.Analyze( semanticModel, syntaxFacts, objectCreation, cancellationToken); if (matches == null || matches.Value.Length == 0) { continue; } var statement = objectCreation.FirstAncestorOrSelf<TStatementSyntax>(); Contract.ThrowIfNull(statement); var newStatement = GetNewStatement(statement, objectCreation, matches.Value) .WithAdditionalAnnotations(Formatter.Annotation); var subEditor = new SyntaxEditor(currentRoot, workspace); subEditor.ReplaceNode(statement, newStatement); foreach (var match in matches) { subEditor.RemoveNode(match.Statement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } document = document.WithSyntaxRoot(subEditor.GetChangedRoot()); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); currentRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } editor.ReplaceNode(editor.OriginalRoot, currentRoot); } protected abstract TStatementSyntax GetNewStatement( TStatementSyntax statement, TObjectCreationExpressionSyntax objectCreation, ImmutableArray<Match<TExpressionSyntax, TStatementSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax>> matches); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Object_initialization_can_be_simplified, createChangedDocument, nameof(AnalyzersResources.Object_initialization_can_be_simplified)) { } } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal enum ClosureKind { /// <summary> /// The closure doesn't declare any variables, and is never converted to a delegate. /// Lambdas are emitted directly to the containing class as a static method. /// </summary> Static, /// <summary> /// The closure doesn't declare any variables, and is converted to a delegate at least once. /// Display class is a singleton and may be shared with other top-level methods. /// </summary> Singleton, /// <summary> /// The closure only contains a reference to the containing class instance ("this"). /// We don't emit a display class, lambdas are emitted directly to the containing class as its instance methods. /// </summary> ThisOnly, /// <summary> /// General closure. /// Display class may only contain lambdas defined in the same top-level method. /// </summary> General, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal enum ClosureKind { /// <summary> /// The closure doesn't declare any variables, and is never converted to a delegate. /// Lambdas are emitted directly to the containing class as a static method. /// </summary> Static, /// <summary> /// The closure doesn't declare any variables, and is converted to a delegate at least once. /// Display class is a singleton and may be shared with other top-level methods. /// </summary> Singleton, /// <summary> /// The closure only contains a reference to the containing class instance ("this"). /// We don't emit a display class, lambdas are emitted directly to the containing class as its instance methods. /// </summary> ThisOnly, /// <summary> /// General closure. /// Display class may only contain lambdas defined in the same top-level method. /// </summary> General, } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Workspaces/CSharp/Portable/CodeGeneration/EnumMemberGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class EnumMemberGenerator { internal static EnumDeclarationSyntax AddEnumMemberTo(EnumDeclarationSyntax destination, IFieldSymbol enumMember, CodeGenerationOptions options) { var members = new List<SyntaxNodeOrToken>(); members.AddRange(destination.Members.GetWithSeparators()); var member = GenerateEnumMemberDeclaration(enumMember, destination, options); if (members.Count == 0) { members.Add(member); } else if (members.LastOrDefault().Kind() == SyntaxKind.CommaToken) { members.Add(member); members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); } else { var lastMember = members.Last(); var trailingTrivia = lastMember.GetTrailingTrivia(); members[members.Count - 1] = lastMember.WithTrailingTrivia(); members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(trailingTrivia)); members.Add(member); } return destination.EnsureOpenAndCloseBraceTokens() .WithMembers(SyntaxFactory.SeparatedList<EnumMemberDeclarationSyntax>(members)); } public static EnumMemberDeclarationSyntax GenerateEnumMemberDeclaration( IFieldSymbol enumMember, EnumDeclarationSyntax destinationOpt, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<EnumMemberDeclarationSyntax>(enumMember, options); if (reusableSyntax != null) { return reusableSyntax; } var value = CreateEnumMemberValue(destinationOpt, enumMember); var member = SyntaxFactory.EnumMemberDeclaration(enumMember.Name.ToIdentifierToken()) .WithEqualsValue(value == null ? null : SyntaxFactory.EqualsValueClause(value: value)); return AddFormatterAndCodeGeneratorAnnotationsTo( ConditionallyAddDocumentationCommentTo(member, enumMember, options)); } private static ExpressionSyntax CreateEnumMemberValue(EnumDeclarationSyntax destinationOpt, IFieldSymbol enumMember) { if (!enumMember.HasConstantValue) { return null; } if (enumMember.ConstantValue is not byte and not sbyte and not ushort and not short and not int and not uint and not long and not ulong) { return null; } var value = IntegerUtilities.ToInt64(enumMember.ConstantValue); if (destinationOpt != null) { if (destinationOpt.Members.Count == 0) { if (value == 0) { return null; } } else { // Don't generate an initializer if no other members have them, and our value // would be correctly inferred from our position. if (destinationOpt.Members.Count == value && destinationOpt.Members.All(m => m.EqualsValue == null)) { return null; } // Existing members, try to stay consistent with their style. var lastMember = destinationOpt.Members.LastOrDefault(m => m.EqualsValue != null); if (lastMember != null) { var lastExpression = lastMember.EqualsValue.Value; if (lastExpression.Kind() == SyntaxKind.LeftShiftExpression && IntegerUtilities.HasOneBitSet(value)) { var binaryExpression = (BinaryExpressionSyntax)lastExpression; if (binaryExpression.Left.Kind() == SyntaxKind.NumericLiteralExpression) { var numericLiteral = (LiteralExpressionSyntax)binaryExpression.Left; if (numericLiteral.Token.ValueText == "1") { // The user is left shifting ones, stick with that pattern var shiftValue = IntegerUtilities.LogBase2(value); // Re-use the numericLiteral text so type suffixes match too return SyntaxFactory.BinaryExpression( SyntaxKind.LeftShiftExpression, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericLiteral.Token.Text, 1)), SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(shiftValue.ToString(), shiftValue))); } } } else if (lastExpression.IsKind(SyntaxKind.NumericLiteralExpression, out LiteralExpressionSyntax numericLiteral)) { var numericToken = numericLiteral.Token; var numericText = numericToken.ToString(); if (numericText.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { // Hex return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericText.Substring(0, 2) + value.ToString("X"), value)); } else if (numericText.StartsWith("0b", StringComparison.OrdinalIgnoreCase)) { return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericText.Substring(0, 2) + Convert.ToString(value, 2), value)); } } } } } var namedType = enumMember.Type as INamedTypeSymbol; var underlyingType = namedType?.EnumUnderlyingType; return ExpressionGenerator.GenerateNonEnumValueExpression( underlyingType, enumMember.ConstantValue, canUseFieldReference: 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; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class EnumMemberGenerator { internal static EnumDeclarationSyntax AddEnumMemberTo(EnumDeclarationSyntax destination, IFieldSymbol enumMember, CodeGenerationOptions options) { var members = new List<SyntaxNodeOrToken>(); members.AddRange(destination.Members.GetWithSeparators()); var member = GenerateEnumMemberDeclaration(enumMember, destination, options); if (members.Count == 0) { members.Add(member); } else if (members.LastOrDefault().Kind() == SyntaxKind.CommaToken) { members.Add(member); members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); } else { var lastMember = members.Last(); var trailingTrivia = lastMember.GetTrailingTrivia(); members[members.Count - 1] = lastMember.WithTrailingTrivia(); members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(trailingTrivia)); members.Add(member); } return destination.EnsureOpenAndCloseBraceTokens() .WithMembers(SyntaxFactory.SeparatedList<EnumMemberDeclarationSyntax>(members)); } public static EnumMemberDeclarationSyntax GenerateEnumMemberDeclaration( IFieldSymbol enumMember, EnumDeclarationSyntax destinationOpt, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<EnumMemberDeclarationSyntax>(enumMember, options); if (reusableSyntax != null) { return reusableSyntax; } var value = CreateEnumMemberValue(destinationOpt, enumMember); var member = SyntaxFactory.EnumMemberDeclaration(enumMember.Name.ToIdentifierToken()) .WithEqualsValue(value == null ? null : SyntaxFactory.EqualsValueClause(value: value)); return AddFormatterAndCodeGeneratorAnnotationsTo( ConditionallyAddDocumentationCommentTo(member, enumMember, options)); } private static ExpressionSyntax CreateEnumMemberValue(EnumDeclarationSyntax destinationOpt, IFieldSymbol enumMember) { if (!enumMember.HasConstantValue) { return null; } if (enumMember.ConstantValue is not byte and not sbyte and not ushort and not short and not int and not uint and not long and not ulong) { return null; } var value = IntegerUtilities.ToInt64(enumMember.ConstantValue); if (destinationOpt != null) { if (destinationOpt.Members.Count == 0) { if (value == 0) { return null; } } else { // Don't generate an initializer if no other members have them, and our value // would be correctly inferred from our position. if (destinationOpt.Members.Count == value && destinationOpt.Members.All(m => m.EqualsValue == null)) { return null; } // Existing members, try to stay consistent with their style. var lastMember = destinationOpt.Members.LastOrDefault(m => m.EqualsValue != null); if (lastMember != null) { var lastExpression = lastMember.EqualsValue.Value; if (lastExpression.Kind() == SyntaxKind.LeftShiftExpression && IntegerUtilities.HasOneBitSet(value)) { var binaryExpression = (BinaryExpressionSyntax)lastExpression; if (binaryExpression.Left.Kind() == SyntaxKind.NumericLiteralExpression) { var numericLiteral = (LiteralExpressionSyntax)binaryExpression.Left; if (numericLiteral.Token.ValueText == "1") { // The user is left shifting ones, stick with that pattern var shiftValue = IntegerUtilities.LogBase2(value); // Re-use the numericLiteral text so type suffixes match too return SyntaxFactory.BinaryExpression( SyntaxKind.LeftShiftExpression, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericLiteral.Token.Text, 1)), SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(shiftValue.ToString(), shiftValue))); } } } else if (lastExpression.IsKind(SyntaxKind.NumericLiteralExpression, out LiteralExpressionSyntax numericLiteral)) { var numericToken = numericLiteral.Token; var numericText = numericToken.ToString(); if (numericText.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { // Hex return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericText.Substring(0, 2) + value.ToString("X"), value)); } else if (numericText.StartsWith("0b", StringComparison.OrdinalIgnoreCase)) { return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericText.Substring(0, 2) + Convert.ToString(value, 2), value)); } } } } } var namedType = enumMember.Type as INamedTypeSymbol; var underlyingType = namedType?.EnumUnderlyingType; return ExpressionGenerator.GenerateNonEnumValueExpression( underlyingType, enumMember.ConstantValue, canUseFieldReference: true); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/YieldKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class YieldKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public YieldKeywordRecommender() : base(SyntaxKind.YieldKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsStatementContext; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class YieldKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public YieldKeywordRecommender() : base(SyntaxKind.YieldKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsStatementContext; } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Test/Core/Compilation/TestOperationVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class TestOperationVisitor : OperationVisitor { public static readonly TestOperationVisitor Singleton = new TestOperationVisitor(); private TestOperationVisitor() : base() { } public override void DefaultVisit(IOperation operation) { throw new NotImplementedException(operation.GetType().ToString()); } internal override void VisitNoneOperation(IOperation operation) { #if Test_IOperation_None_Kind Assert.True(false, "Encountered an IOperation with `Kind == OperationKind.None` while walking the operation tree."); #endif Assert.Equal(OperationKind.None, operation.Kind); } public override void Visit(IOperation operation) { if (operation != null) { var syntax = operation.Syntax; var type = operation.Type; var constantValue = operation.ConstantValue; Assert.NotNull(syntax); // operation.Language can throw due to https://github.com/dotnet/roslyn/issues/23821 // Conditional logic below should be removed once the issue is fixed if (syntax is Microsoft.CodeAnalysis.Syntax.SyntaxList) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Equal(LanguageNames.CSharp, operation.Parent.Language); } else { var language = operation.Language; } var isImplicit = operation.IsImplicit; foreach (IOperation child in operation.Children) { Assert.NotNull(child); } if (operation.SemanticModel != null) { Assert.Same(operation.SemanticModel, operation.SemanticModel.ContainingModelOrSelf); } } base.Visit(operation); } public override void VisitBlock(IBlockOperation operation) { Assert.Equal(OperationKind.Block, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Operations, operation.Children); } public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) { Assert.Equal(OperationKind.VariableDeclarationGroup, operation.Kind); AssertEx.Equal(operation.Declarations, operation.Children); } public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { Assert.Equal(OperationKind.VariableDeclarator, operation.Kind); Assert.NotNull(operation.Symbol); IEnumerable<IOperation> children = operation.IgnoredArguments; var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitVariableDeclaration(IVariableDeclarationOperation operation) { Assert.Equal(OperationKind.VariableDeclaration, operation.Kind); IEnumerable<IOperation> children = operation.IgnoredDimensions.Concat(operation.Declarators); var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitSwitch(ISwitchOperation operation) { Assert.Equal(OperationKind.Switch, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ExitLabel); AssertEx.Equal(new[] { operation.Value }.Concat(operation.Cases), operation.Children); } public override void VisitSwitchCase(ISwitchCaseOperation operation) { Assert.Equal(OperationKind.SwitchCase, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Clauses.Concat(operation.Body), operation.Children); VerifySubTree(((SwitchCaseOperation)operation).Condition, hasNonNullParent: true); } internal static void VerifySubTree(IOperation root, bool hasNonNullParent = false) { if (root != null) { if (hasNonNullParent) { // This is only ever true for ISwitchCaseOperation.Condition. Assert.NotNull(root.Parent); Assert.Same(root, ((SwitchCaseOperation)root.Parent).Condition); } else { Assert.Null(root.Parent); } var explicitNodeMap = new Dictionary<SyntaxNode, IOperation>(); foreach (IOperation descendant in root.DescendantsAndSelf()) { if (!descendant.IsImplicit) { try { explicitNodeMap.Add(descendant.Syntax, descendant); } catch (ArgumentException) { Assert.False(true, $"Duplicate explicit node for syntax ({descendant.Syntax.RawKind}): {descendant.Syntax.ToString()}"); } } Singleton.Visit(descendant); } } } public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.SingleValue, operation.CaseKind); AssertEx.Equal(new[] { operation.Value }, operation.Children); } private static void VisitCaseClauseOperation(ICaseClauseOperation operation) { Assert.Equal(OperationKind.CaseClause, operation.Kind); _ = operation.Label; } public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Relational, operation.CaseKind); var relation = operation.Relation; AssertEx.Equal(new[] { operation.Value }, operation.Children); } public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Default, operation.CaseKind); Assert.Empty(operation.Children); } private static void VisitLocals(ImmutableArray<ILocalSymbol> locals) { foreach (var local in locals) { Assert.NotNull(local); } } public override void VisitWhileLoop(IWhileLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.While, operation.LoopKind); var conditionIsTop = operation.ConditionIsTop; var conditionIsUntil = operation.ConditionIsUntil; IEnumerable<IOperation> children; if (conditionIsTop) { if (operation.IgnoredCondition != null) { children = new[] { operation.Condition, operation.Body, operation.IgnoredCondition }; } else { children = new[] { operation.Condition, operation.Body }; } } else { Assert.Null(operation.IgnoredCondition); if (operation.Condition != null) { children = new[] { operation.Body, operation.Condition }; } else { children = new[] { operation.Body }; } } AssertEx.Equal(children, operation.Children); } public override void VisitForLoop(IForLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.For, operation.LoopKind); VisitLocals(operation.Locals); VisitLocals(operation.ConditionLocals); IEnumerable<IOperation> children = operation.Before; if (operation.Condition != null) { children = children.Concat(new[] { operation.Condition }); } children = children.Concat(new[] { operation.Body }); children = children.Concat(operation.AtLoopBottom); AssertEx.Equal(children, operation.Children); } public override void VisitForToLoop(IForToLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForTo, operation.LoopKind); _ = operation.IsChecked; (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; if (userDefinedInfo != null) { VerifySubTree(userDefinedInfo.Addition); VerifySubTree(userDefinedInfo.Subtraction); VerifySubTree(userDefinedInfo.LessThanOrEqual); VerifySubTree(userDefinedInfo.GreaterThanOrEqual); } IEnumerable<IOperation> children; children = new[] { operation.LoopControlVariable, operation.InitialValue, operation.LimitValue, operation.StepValue, operation.Body }; children = children.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); } public override void VisitForEachLoop(IForEachLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForEach, operation.LoopKind); IEnumerable<IOperation> children = new[] { operation.Collection, operation.LoopControlVariable, operation.Body }.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; if (info != null) { visitArguments(info.GetEnumeratorArguments); visitArguments(info.MoveNextArguments); visitArguments(info.CurrentArguments); visitArguments(info.DisposeArguments); } void visitArguments(ImmutableArray<IArgumentOperation> arguments) { if (arguments != null) { foreach (IArgumentOperation arg in arguments) { VerifySubTree(arg); } } } } private static void VisitLoop(ILoopOperation operation) { Assert.Equal(OperationKind.Loop, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ContinueLabel); Assert.NotNull(operation.ExitLabel); } public override void VisitLabeled(ILabeledOperation operation) { Assert.Equal(OperationKind.Labeled, operation.Kind); Assert.NotNull(operation.Label); if (operation.Operation == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Operation, operation.Children.Single()); } } public override void VisitBranch(IBranchOperation operation) { Assert.Equal(OperationKind.Branch, operation.Kind); Assert.NotNull(operation.Target); switch (operation.BranchKind) { case BranchKind.Break: case BranchKind.Continue: case BranchKind.GoTo: break; default: Assert.False(true); break; } Assert.Empty(operation.Children); } public override void VisitEmpty(IEmptyOperation operation) { Assert.Equal(OperationKind.Empty, operation.Kind); Assert.Empty(operation.Children); } public override void VisitReturn(IReturnOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Return, OperationKind.YieldReturn, OperationKind.YieldBreak }); if (operation.ReturnedValue == null) { Assert.NotEqual(OperationKind.YieldReturn, operation.Kind); Assert.Empty(operation.Children); } else { Assert.Same(operation.ReturnedValue, operation.Children.Single()); } } public override void VisitLock(ILockOperation operation) { Assert.Equal(OperationKind.Lock, operation.Kind); AssertEx.Equal(new[] { operation.LockedValue, operation.Body }, operation.Children); } public override void VisitTry(ITryOperation operation) { Assert.Equal(OperationKind.Try, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Body }; _ = operation.ExitLabel; children = children.Concat(operation.Catches); if (operation.Finally != null) { children = children.Concat(new[] { operation.Finally }); } AssertEx.Equal(children, operation.Children); } public override void VisitCatchClause(ICatchClauseOperation operation) { Assert.Equal(OperationKind.CatchClause, operation.Kind); var exceptionType = operation.ExceptionType; VisitLocals(operation.Locals); IEnumerable<IOperation> children = Array.Empty<IOperation>(); if (operation.ExceptionDeclarationOrExpression != null) { children = children.Concat(new[] { operation.ExceptionDeclarationOrExpression }); } if (operation.Filter != null) { children = children.Concat(new[] { operation.Filter }); } children = children.Concat(new[] { operation.Handler }); AssertEx.Equal(children, operation.Children); } public override void VisitUsing(IUsingOperation operation) { Assert.Equal(OperationKind.Using, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Resources, operation.Body }, operation.Children); Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind); Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind); _ = ((UsingOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } // https://github.com/dotnet/roslyn/issues/21281 internal override void VisitFixed(IFixedOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Variables, operation.Body }, operation.Children); } internal override void VisitAggregateQuery(IAggregateQueryOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Group, operation.Aggregation }, operation.Children); } public override void VisitExpressionStatement(IExpressionStatementOperation operation) { Assert.Equal(OperationKind.ExpressionStatement, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } internal override void VisitWithStatement(IWithStatementOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Body }, operation.Children); } public override void VisitStop(IStopOperation operation) { Assert.Equal(OperationKind.Stop, operation.Kind); Assert.Empty(operation.Children); } public override void VisitEnd(IEndOperation operation) { Assert.Equal(OperationKind.End, operation.Kind); Assert.Empty(operation.Children); } public override void VisitInvocation(IInvocationOperation operation) { Assert.Equal(OperationKind.Invocation, operation.Kind); Assert.NotNull(operation.TargetMethod); var isVirtual = operation.IsVirtual; IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(operation.Arguments); } else { children = operation.Arguments; } AssertEx.Equal(children, operation.Children); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.TargetMethod.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } public override void VisitArgument(IArgumentOperation operation) { Assert.Equal(OperationKind.Argument, operation.Kind); Assert.Contains(operation.ArgumentKind, new[] { ArgumentKind.DefaultValue, ArgumentKind.Explicit, ArgumentKind.ParamArray }); var parameter = operation.Parameter; Assert.Same(operation.Value, operation.Children.Single()); var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.ArgumentKind == ArgumentKind.DefaultValue) { Assert.True(operation.Descendants().All(n => n.IsImplicit), $"Explicit node in default argument value ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}"); } } public override void VisitOmittedArgument(IOmittedArgumentOperation operation) { Assert.Equal(OperationKind.OmittedArgument, operation.Kind); Assert.Empty(operation.Children); } public override void VisitArrayElementReference(IArrayElementReferenceOperation operation) { Assert.Equal(OperationKind.ArrayElementReference, operation.Kind); AssertEx.Equal(new[] { operation.ArrayReference }.Concat(operation.Indices), operation.Children); } internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Same(operation.Pointer, operation.Children.Single()); } public override void VisitLocalReference(ILocalReferenceOperation operation) { Assert.Equal(OperationKind.LocalReference, operation.Kind); Assert.NotNull(operation.Local); var isDeclaration = operation.IsDeclaration; Assert.Empty(operation.Children); } public override void VisitParameterReference(IParameterReferenceOperation operation) { Assert.Equal(OperationKind.ParameterReference, operation.Kind); Assert.NotNull(operation.Parameter); Assert.Empty(operation.Children); } public override void VisitInstanceReference(IInstanceReferenceOperation operation) { Assert.Equal(OperationKind.InstanceReference, operation.Kind); Assert.Empty(operation.Children); var referenceKind = operation.ReferenceKind; } private void VisitMemberReference(IMemberReferenceOperation operation) { VisitMemberReference(operation, Array.Empty<IOperation>()); } private void VisitMemberReference(IMemberReferenceOperation operation, IEnumerable<IOperation> additionalChildren) { Assert.NotNull(operation.Member); IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(additionalChildren); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.Member.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } else { children = additionalChildren; } AssertEx.Equal(children, operation.Children); } public override void VisitFieldReference(IFieldReferenceOperation operation) { Assert.Equal(OperationKind.FieldReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Field); var isDeclaration = operation.IsDeclaration; } public override void VisitMethodReference(IMethodReferenceOperation operation) { Assert.Equal(OperationKind.MethodReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Method); var isVirtual = operation.IsVirtual; } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { Assert.Equal(OperationKind.PropertyReference, operation.Kind); VisitMemberReference(operation, operation.Arguments); Assert.Same(operation.Member, operation.Property); } public override void VisitEventReference(IEventReferenceOperation operation) { Assert.Equal(OperationKind.EventReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Event); } public override void VisitEventAssignment(IEventAssignmentOperation operation) { Assert.Equal(OperationKind.EventAssignment, operation.Kind); var adds = operation.Adds; AssertEx.Equal(new[] { operation.EventReference, operation.HandlerValue }, operation.Children); } public override void VisitConditionalAccess(IConditionalAccessOperation operation) { Assert.Equal(OperationKind.ConditionalAccess, operation.Kind); Assert.NotNull(operation.Type); AssertEx.Equal(new[] { operation.Operation, operation.WhenNotNull }, operation.Children); } public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) { Assert.Equal(OperationKind.ConditionalAccessInstance, operation.Kind); Assert.Empty(operation.Children); } internal override void VisitPlaceholder(IPlaceholderOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Empty(operation.Children); } public override void VisitUnaryOperator(IUnaryOperation operation) { Assert.Equal(OperationKind.UnaryOperator, operation.Kind); Assert.Equal(OperationKind.Unary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitBinaryOperator(IBinaryOperation operation) { Assert.Equal(OperationKind.BinaryOperator, operation.Kind); Assert.Equal(OperationKind.Binary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod; var binaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; var isCompareText = operation.IsCompareText; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation) { Assert.Equal(OperationKind.TupleBinaryOperator, operation.Kind); Assert.Equal(OperationKind.TupleBinary, operation.Kind); var binaryOperationKind = operation.OperatorKind; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitConversion(IConversionOperation operation) { Assert.Equal(OperationKind.Conversion, operation.Kind); var operatorMethod = operation.OperatorMethod; var conversion = operation.Conversion; var isChecked = operation.IsChecked; var isTryCast = operation.IsTryCast; switch (operation.Language) { case LanguageNames.CSharp: CSharp.Conversion csharpConversion = CSharp.CSharpExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => VisualBasic.VisualBasicExtensions.GetConversion(operation)); break; case LanguageNames.VisualBasic: VisualBasic.Conversion visualBasicConversion = VisualBasic.VisualBasicExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => CSharp.CSharpExtensions.GetConversion(operation)); break; default: Debug.Fail($"Language {operation.Language} is unknown!"); break; } Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitConditional(IConditionalOperation operation) { Assert.Equal(OperationKind.Conditional, operation.Kind); bool isRef = operation.IsRef; if (operation.WhenFalse != null) { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue, operation.WhenFalse }, operation.Children); } else { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue }, operation.Children); } } public override void VisitCoalesce(ICoalesceOperation operation) { Assert.Equal(OperationKind.Coalesce, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.WhenNull }, operation.Children); var valueConversion = operation.ValueConversion; } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { Assert.Equal(OperationKind.CoalesceAssignment, operation.Kind); AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitIsType(IIsTypeOperation operation) { Assert.Equal(OperationKind.IsType, operation.Kind); Assert.NotNull(operation.TypeOperand); bool isNegated = operation.IsNegated; Assert.Same(operation.ValueOperand, operation.Children.Single()); } public override void VisitSizeOf(ISizeOfOperation operation) { Assert.Equal(OperationKind.SizeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitTypeOf(ITypeOfOperation operation) { Assert.Equal(OperationKind.TypeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.AnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Same(operation.Body, operation.Children.Single()); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.FlowAnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Empty(operation.Children); } public override void VisitLocalFunction(ILocalFunctionOperation operation) { Assert.Equal(OperationKind.LocalFunction, operation.Kind); Assert.NotNull(operation.Symbol); if (operation.Body != null) { var children = operation.Children.ToImmutableArray(); Assert.Same(operation.Body, children[0]); if (operation.IgnoredBody != null) { Assert.Same(operation.IgnoredBody, children[1]); Assert.Equal(2, children.Length); } else { Assert.Equal(1, children.Length); } } else { Assert.Null(operation.IgnoredBody); Assert.Empty(operation.Children); } } public override void VisitLiteral(ILiteralOperation operation) { Assert.Equal(OperationKind.Literal, operation.Kind); Assert.Empty(operation.Children); } public override void VisitAwait(IAwaitOperation operation) { Assert.Equal(OperationKind.Await, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitNameOf(INameOfOperation operation) { Assert.Equal(OperationKind.NameOf, operation.Kind); Assert.Same(operation.Argument, operation.Children.Single()); } public override void VisitThrow(IThrowOperation operation) { Assert.Equal(OperationKind.Throw, operation.Kind); if (operation.Exception == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Exception, operation.Children.Single()); } } public override void VisitAddressOf(IAddressOfOperation operation) { Assert.Equal(OperationKind.AddressOf, operation.Kind); Assert.Same(operation.Reference, operation.Children.Single()); } public override void VisitObjectCreation(IObjectCreationOperation operation) { Assert.Equal(OperationKind.ObjectCreation, operation.Kind); var constructor = operation.Constructor; // When parameter-less struct constructor is inaccessible, the constructor symbol is null if (!operation.Type.IsValueType) { Assert.NotNull(constructor); if (constructor == null) { Assert.Empty(operation.Arguments); } } IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) { Assert.Equal(OperationKind.AnonymousObjectCreation, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); foreach (var initializer in operation.Initializers) { var simpleAssignment = (ISimpleAssignmentOperation)initializer; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Assert.Empty(propertyReference.Arguments); Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind); Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind); } } public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) { Assert.Equal(OperationKind.DynamicObjectCreation, operation.Kind); IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitDynamicInvocation(IDynamicInvocationOperation operation) { Assert.Equal(OperationKind.DynamicInvocation, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) { Assert.Equal(OperationKind.DynamicIndexerAccess, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) { Assert.Equal(OperationKind.ObjectOrCollectionInitializer, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); } public override void VisitMemberInitializer(IMemberInitializerOperation operation) { Assert.Equal(OperationKind.MemberInitializer, operation.Kind); AssertEx.Equal(new[] { operation.InitializedMember, operation.Initializer }, operation.Children); } private void VisitSymbolInitializer(ISymbolInitializerOperation operation) { VisitLocals(operation.Locals); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitFieldInitializer(IFieldInitializerOperation operation) { Assert.Equal(OperationKind.FieldInitializer, operation.Kind); foreach (var field in operation.InitializedFields) { Assert.NotNull(field); } VisitSymbolInitializer(operation); } public override void VisitVariableInitializer(IVariableInitializerOperation operation) { Assert.Equal(OperationKind.VariableInitializer, operation.Kind); Assert.Empty(operation.Locals); VisitSymbolInitializer(operation); } public override void VisitPropertyInitializer(IPropertyInitializerOperation operation) { Assert.Equal(OperationKind.PropertyInitializer, operation.Kind); foreach (var property in operation.InitializedProperties) { Assert.NotNull(property); } VisitSymbolInitializer(operation); } public override void VisitParameterInitializer(IParameterInitializerOperation operation) { Assert.Equal(OperationKind.ParameterInitializer, operation.Kind); Assert.NotNull(operation.Parameter); VisitSymbolInitializer(operation); } public override void VisitArrayCreation(IArrayCreationOperation operation) { Assert.Equal(OperationKind.ArrayCreation, operation.Kind); IEnumerable<IOperation> children = operation.DimensionSizes; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitArrayInitializer(IArrayInitializerOperation operation) { Assert.Equal(OperationKind.ArrayInitializer, operation.Kind); Assert.Null(operation.Type); AssertEx.Equal(operation.ElementValues, operation.Children); } private void VisitAssignment(IAssignmentOperation operation) { AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { Assert.Equal(OperationKind.SimpleAssignment, operation.Kind); bool isRef = operation.IsRef; VisitAssignment(operation); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { Assert.Equal(OperationKind.CompoundAssignment, operation.Kind); var operatorMethod = operation.OperatorMethod; var binaryOperationKind = operation.OperatorKind; var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.Syntax.Language == LanguageNames.CSharp) { Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetOutConversion(operation)); var inConversionInternal = CSharp.CSharpExtensions.GetInConversion(operation); var outConversionInternal = CSharp.CSharpExtensions.GetOutConversion(operation); } else { Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetOutConversion(operation)); var inConversionInternal = VisualBasic.VisualBasicExtensions.GetInConversion(operation); var outConversionInternal = VisualBasic.VisualBasicExtensions.GetOutConversion(operation); } var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; VisitAssignment(operation); } public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Increment, OperationKind.Decrement }); var operatorMethod = operation.OperatorMethod; var isPostFix = operation.IsPostfix; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitParenthesized(IParenthesizedOperation operation) { Assert.Equal(OperationKind.Parenthesized, operation.Kind); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) { Assert.Equal(OperationKind.DynamicMemberReference, operation.Kind); Assert.NotNull(operation.MemberName); foreach (var typeArg in operation.TypeArguments) { Assert.NotNull(typeArg); } var containingType = operation.ContainingType; if (operation.Instance == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Instance, operation.Children.Single()); } } public override void VisitDefaultValue(IDefaultValueOperation operation) { Assert.Equal(OperationKind.DefaultValue, operation.Kind); Assert.Empty(operation.Children); } public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) { Assert.Equal(OperationKind.TypeParameterObjectCreation, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } public override void VisitInvalid(IInvalidOperation operation) { Assert.Equal(OperationKind.Invalid, operation.Kind); } public override void VisitTuple(ITupleOperation operation) { Assert.Equal(OperationKind.Tuple, operation.Kind); var naturalType = operation.NaturalType; AssertEx.Equal(operation.Elements, operation.Children); } public override void VisitInterpolatedString(IInterpolatedStringOperation operation) { Assert.Equal(OperationKind.InterpolatedString, operation.Kind); AssertEx.Equal(operation.Parts, operation.Children); } public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) { Assert.Equal(OperationKind.InterpolatedStringText, operation.Kind); if (operation.Text.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind); } Assert.Same(operation.Text, operation.Children.Single()); } public override void VisitInterpolation(IInterpolationOperation operation) { Assert.Equal(OperationKind.Interpolation, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Expression }; if (operation.Alignment != null) { children = children.Concat(new[] { operation.Alignment }); } if (operation.FormatString != null) { if (operation.FormatString.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind); } children = children.Concat(new[] { operation.FormatString }); } AssertEx.Equal(children, operation.Children); } private void VisitPatternCommon(IPatternOperation pattern) { Assert.NotNull(pattern.InputType); Assert.NotNull(pattern.NarrowedType); Assert.Null(pattern.Type); Assert.False(pattern.ConstantValue.HasValue); } public override void VisitConstantPattern(IConstantPatternOperation operation) { Assert.Equal(OperationKind.ConstantPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitRelationalPattern(IRelationalPatternOperation operation) { Assert.Equal(OperationKind.RelationalPattern, operation.Kind); Assert.True(operation.OperatorKind is Operations.BinaryOperatorKind.LessThan or Operations.BinaryOperatorKind.LessThanOrEqual or Operations.BinaryOperatorKind.GreaterThan or Operations.BinaryOperatorKind.GreaterThanOrEqual or Operations.BinaryOperatorKind.Equals or // Error cases Operations.BinaryOperatorKind.NotEquals); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitBinaryPattern(IBinaryPatternOperation operation) { Assert.Equal(OperationKind.BinaryPattern, operation.Kind); VisitPatternCommon(operation); Assert.True(operation.OperatorKind switch { Operations.BinaryOperatorKind.Or => true, Operations.BinaryOperatorKind.And => true, _ => false }); var children = operation.Children.ToArray(); Assert.Equal(2, children.Length); Assert.Same(operation.LeftPattern, children[0]); Assert.Same(operation.RightPattern, children[1]); } public override void VisitNegatedPattern(INegatedPatternOperation operation) { Assert.Equal(OperationKind.NegatedPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Pattern, operation.Children.Single()); } public override void VisitTypePattern(ITypePatternOperation operation) { Assert.Equal(OperationKind.TypePattern, operation.Kind); Assert.NotNull(operation.MatchedType); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { Assert.Equal(OperationKind.DeclarationPattern, operation.Kind); VisitPatternCommon(operation); if (operation.Syntax.IsKind(CSharp.SyntaxKind.VarPattern) || // in `var (x, y)`, the syntax here is the designation `x`. operation.Syntax.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.True(operation.MatchesNull); Assert.Null(operation.MatchedType); } else { Assert.False(operation.MatchesNull); Assert.NotNull(operation.MatchedType); } var designation = (operation.Syntax as CSharp.Syntax.DeclarationPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VarPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VariableDesignationSyntax); if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } Assert.Empty(operation.Children); } public override void VisitRecursivePattern(IRecursivePatternOperation operation) { Assert.Equal(OperationKind.RecursivePattern, operation.Kind); VisitPatternCommon(operation); Assert.NotNull(operation.MatchedType); switch (operation.DeconstructSymbol) { case IErrorTypeSymbol error: case null: // OK: indicates deconstruction of a tuple, or an error case break; case IMethodSymbol method: // when we have a method, it is a `Deconstruct` method Assert.Equal("Deconstruct", method.Name); break; case ITypeSymbol type: // when we have a type, it is the type "ITuple" Assert.Equal("ITuple", type.Name); break; default: Assert.True(false, $"Unexpected symbol {operation.DeconstructSymbol}"); break; } var designation = (operation.Syntax as CSharp.Syntax.RecursivePatternSyntax)?.Designation; if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } foreach (var subpat in operation.PropertySubpatterns) { Assert.True(subpat is IPropertySubpatternOperation); } IEnumerable<IOperation> children = operation.DeconstructionSubpatterns.Cast<IOperation>(); children = children.Concat(operation.PropertySubpatterns); AssertEx.Equal(children, operation.Children); } public override void VisitPropertySubpattern(IPropertySubpatternOperation operation) { Assert.NotNull(operation.Pattern); var children = new IOperation[] { operation.Member, operation.Pattern }; AssertEx.Equal(children, operation.Children); if (operation.Member.Kind == OperationKind.Invalid) { return; } Assert.True(operation.Member is IMemberReferenceOperation); var member = (IMemberReferenceOperation)operation.Member; switch (member.Member) { case IFieldSymbol field: case IPropertySymbol prop: break; case var symbol: Assert.True(false, $"Unexpected symbol {symbol}"); break; } } public override void VisitSwitchExpression(ISwitchExpressionOperation operation) { //force the existence of IsExhaustive _ = operation.IsExhaustive; Assert.NotNull(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.Equal(OperationKind.SwitchExpression, operation.Kind); Assert.NotNull(operation.Value); var children = operation.Arms.Cast<IOperation>().Prepend(operation.Value); AssertEx.Equal(children, operation.Children); } public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) { Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.NotNull(operation.Pattern); _ = operation.Guard; Assert.NotNull(operation.Value); VisitLocals(operation.Locals); var children = operation.Guard == null ? new[] { operation.Pattern, operation.Value } : new[] { operation.Pattern, operation.Guard, operation.Value }; AssertEx.Equal(children, operation.Children); } public override void VisitIsPattern(IIsPatternOperation operation) { Assert.Equal(OperationKind.IsPattern, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Pattern }, operation.Children); } public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Pattern, operation.CaseKind); Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label); if (operation.Guard != null) { AssertEx.Equal(new[] { operation.Pattern, operation.Guard }, operation.Children); } else { Assert.Same(operation.Pattern, operation.Children.Single()); } } public override void VisitTranslatedQuery(ITranslatedQueryOperation operation) { Assert.Equal(OperationKind.TranslatedQuery, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation) { Assert.Equal(OperationKind.DeclarationExpression, operation.Kind); Assert.Same(operation.Expression, operation.Children.Single()); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { Assert.Equal(OperationKind.DeconstructionAssignment, operation.Kind); VisitAssignment(operation); } public override void VisitDelegateCreation(IDelegateCreationOperation operation) { Assert.Equal(OperationKind.DelegateCreation, operation.Kind); Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitRaiseEvent(IRaiseEventOperation operation) { Assert.Equal(OperationKind.RaiseEvent, operation.Kind); AssertEx.Equal(new IOperation[] { operation.EventReference }.Concat(operation.Arguments), operation.Children); } public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Range, operation.CaseKind); AssertEx.Equal(new[] { operation.MinimumValue, operation.MaximumValue }, operation.Children); } public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation) { Assert.Equal(OperationKind.ConstructorBodyOperation, operation.Kind); Assert.Equal(OperationKind.ConstructorBody, operation.Kind); VisitLocals(operation.Locals); var builder = ArrayBuilder<IOperation>.GetInstance(); if (operation.Initializer != null) { builder.Add(operation.Initializer); } if (operation.BlockBody != null) { builder.Add(operation.BlockBody); } if (operation.ExpressionBody != null) { builder.Add(operation.ExpressionBody); } AssertEx.Equal(builder, operation.Children); builder.Free(); } public override void VisitMethodBodyOperation(IMethodBodyOperation operation) { Assert.Equal(OperationKind.MethodBodyOperation, operation.Kind); Assert.Equal(OperationKind.MethodBody, operation.Kind); if (operation.BlockBody != null) { if (operation.ExpressionBody != null) { AssertEx.Equal(new[] { operation.BlockBody, operation.ExpressionBody }, operation.Children); } else { Assert.Same(operation.BlockBody, operation.Children.Single()); } } else if (operation.ExpressionBody != null) { Assert.Same(operation.ExpressionBody, operation.Children.Single()); } else { Assert.Empty(operation.Children); } } public override void VisitDiscardOperation(IDiscardOperation operation) { Assert.Equal(OperationKind.Discard, operation.Kind); Assert.Empty(operation.Children); var discardSymbol = operation.DiscardSymbol; Assert.Equal(operation.Type, discardSymbol.Type); } public override void VisitDiscardPattern(IDiscardPatternOperation operation) { Assert.Equal(OperationKind.DiscardPattern, operation.Kind); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitFlowCapture(IFlowCaptureOperation operation) { Assert.Equal(OperationKind.FlowCapture, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Value, operation.Children.Single()); switch (operation.Value.Kind) { case OperationKind.Invalid: case OperationKind.None: case OperationKind.AnonymousFunction: case OperationKind.FlowCaptureReference: case OperationKind.DefaultValue: case OperationKind.FlowAnonymousFunction: // must be an error case like in Microsoft.CodeAnalysis.CSharp.UnitTests.ConditionalOperatorTests.TestBothUntyped unit-test break; case OperationKind.OmittedArgument: case OperationKind.DeclarationExpression: case OperationKind.Discard: Assert.False(true, $"A {operation.Value.Kind} node should not be spilled or captured."); break; default: // Only values can be spilled/captured if (!operation.Value.ConstantValue.HasValue || operation.Value.ConstantValue.Value != null) { Assert.NotNull(operation.Value.Type); } break; } } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { Assert.Equal(OperationKind.FlowCaptureReference, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitIsNull(IIsNullOperation operation) { Assert.Equal(OperationKind.IsNull, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitCaughtException(ICaughtExceptionOperation operation) { Assert.Equal(OperationKind.CaughtException, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) { Assert.Equal(OperationKind.StaticLocalInitializationSemaphore, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); Assert.NotNull(operation.Local); Assert.True(operation.Local.IsStatic); } public override void VisitRangeOperation(IRangeOperation operation) { Assert.Equal(OperationKind.Range, operation.Kind); IOperation[] children = operation.Children.ToArray(); int index = 0; if (operation.LeftOperand != null) { Assert.Same(operation.LeftOperand, children[index++]); } if (operation.RightOperand != null) { Assert.Same(operation.RightOperand, children[index++]); } Assert.Equal(index, children.Length); } public override void VisitReDim(IReDimOperation operation) { Assert.Equal(OperationKind.ReDim, operation.Kind); AssertEx.Equal(operation.Clauses, operation.Children); var preserve = operation.Preserve; } public override void VisitReDimClause(IReDimClauseOperation operation) { Assert.Equal(OperationKind.ReDimClause, operation.Kind); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.DimensionSizes), operation.Children); } public override void VisitUsingDeclaration(IUsingDeclarationOperation operation) { Assert.NotNull(operation.DeclarationGroup); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.DeclarationGroup), operation.Children); Assert.True(operation.DeclarationGroup.IsImplicit); Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); _ = operation.IsAsynchronous; _ = operation.IsImplicit; _ = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } public override void VisitWith(IWithOperation operation) { Assert.Equal(OperationKind.With, operation.Kind); _ = operation.CloneMethod; IEnumerable<IOperation> children = SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.Initializer); AssertEx.Equal(children, operation.Children); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class TestOperationVisitor : OperationVisitor { public static readonly TestOperationVisitor Singleton = new TestOperationVisitor(); private TestOperationVisitor() : base() { } public override void DefaultVisit(IOperation operation) { throw new NotImplementedException(operation.GetType().ToString()); } internal override void VisitNoneOperation(IOperation operation) { #if Test_IOperation_None_Kind Assert.True(false, "Encountered an IOperation with `Kind == OperationKind.None` while walking the operation tree."); #endif Assert.Equal(OperationKind.None, operation.Kind); } public override void Visit(IOperation operation) { if (operation != null) { var syntax = operation.Syntax; var type = operation.Type; var constantValue = operation.ConstantValue; Assert.NotNull(syntax); // operation.Language can throw due to https://github.com/dotnet/roslyn/issues/23821 // Conditional logic below should be removed once the issue is fixed if (syntax is Microsoft.CodeAnalysis.Syntax.SyntaxList) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Equal(LanguageNames.CSharp, operation.Parent.Language); } else { var language = operation.Language; } var isImplicit = operation.IsImplicit; foreach (IOperation child in operation.Children) { Assert.NotNull(child); } if (operation.SemanticModel != null) { Assert.Same(operation.SemanticModel, operation.SemanticModel.ContainingModelOrSelf); } } base.Visit(operation); } public override void VisitBlock(IBlockOperation operation) { Assert.Equal(OperationKind.Block, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Operations, operation.Children); } public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) { Assert.Equal(OperationKind.VariableDeclarationGroup, operation.Kind); AssertEx.Equal(operation.Declarations, operation.Children); } public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { Assert.Equal(OperationKind.VariableDeclarator, operation.Kind); Assert.NotNull(operation.Symbol); IEnumerable<IOperation> children = operation.IgnoredArguments; var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitVariableDeclaration(IVariableDeclarationOperation operation) { Assert.Equal(OperationKind.VariableDeclaration, operation.Kind); IEnumerable<IOperation> children = operation.IgnoredDimensions.Concat(operation.Declarators); var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitSwitch(ISwitchOperation operation) { Assert.Equal(OperationKind.Switch, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ExitLabel); AssertEx.Equal(new[] { operation.Value }.Concat(operation.Cases), operation.Children); } public override void VisitSwitchCase(ISwitchCaseOperation operation) { Assert.Equal(OperationKind.SwitchCase, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Clauses.Concat(operation.Body), operation.Children); VerifySubTree(((SwitchCaseOperation)operation).Condition, hasNonNullParent: true); } internal static void VerifySubTree(IOperation root, bool hasNonNullParent = false) { if (root != null) { if (hasNonNullParent) { // This is only ever true for ISwitchCaseOperation.Condition. Assert.NotNull(root.Parent); Assert.Same(root, ((SwitchCaseOperation)root.Parent).Condition); } else { Assert.Null(root.Parent); } var explicitNodeMap = new Dictionary<SyntaxNode, IOperation>(); foreach (IOperation descendant in root.DescendantsAndSelf()) { if (!descendant.IsImplicit) { try { explicitNodeMap.Add(descendant.Syntax, descendant); } catch (ArgumentException) { Assert.False(true, $"Duplicate explicit node for syntax ({descendant.Syntax.RawKind}): {descendant.Syntax.ToString()}"); } } Singleton.Visit(descendant); } } } public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.SingleValue, operation.CaseKind); AssertEx.Equal(new[] { operation.Value }, operation.Children); } private static void VisitCaseClauseOperation(ICaseClauseOperation operation) { Assert.Equal(OperationKind.CaseClause, operation.Kind); _ = operation.Label; } public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Relational, operation.CaseKind); var relation = operation.Relation; AssertEx.Equal(new[] { operation.Value }, operation.Children); } public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Default, operation.CaseKind); Assert.Empty(operation.Children); } private static void VisitLocals(ImmutableArray<ILocalSymbol> locals) { foreach (var local in locals) { Assert.NotNull(local); } } public override void VisitWhileLoop(IWhileLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.While, operation.LoopKind); var conditionIsTop = operation.ConditionIsTop; var conditionIsUntil = operation.ConditionIsUntil; IEnumerable<IOperation> children; if (conditionIsTop) { if (operation.IgnoredCondition != null) { children = new[] { operation.Condition, operation.Body, operation.IgnoredCondition }; } else { children = new[] { operation.Condition, operation.Body }; } } else { Assert.Null(operation.IgnoredCondition); if (operation.Condition != null) { children = new[] { operation.Body, operation.Condition }; } else { children = new[] { operation.Body }; } } AssertEx.Equal(children, operation.Children); } public override void VisitForLoop(IForLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.For, operation.LoopKind); VisitLocals(operation.Locals); VisitLocals(operation.ConditionLocals); IEnumerable<IOperation> children = operation.Before; if (operation.Condition != null) { children = children.Concat(new[] { operation.Condition }); } children = children.Concat(new[] { operation.Body }); children = children.Concat(operation.AtLoopBottom); AssertEx.Equal(children, operation.Children); } public override void VisitForToLoop(IForToLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForTo, operation.LoopKind); _ = operation.IsChecked; (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; if (userDefinedInfo != null) { VerifySubTree(userDefinedInfo.Addition); VerifySubTree(userDefinedInfo.Subtraction); VerifySubTree(userDefinedInfo.LessThanOrEqual); VerifySubTree(userDefinedInfo.GreaterThanOrEqual); } IEnumerable<IOperation> children; children = new[] { operation.LoopControlVariable, operation.InitialValue, operation.LimitValue, operation.StepValue, operation.Body }; children = children.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); } public override void VisitForEachLoop(IForEachLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForEach, operation.LoopKind); IEnumerable<IOperation> children = new[] { operation.Collection, operation.LoopControlVariable, operation.Body }.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; if (info != null) { visitArguments(info.GetEnumeratorArguments); visitArguments(info.MoveNextArguments); visitArguments(info.CurrentArguments); visitArguments(info.DisposeArguments); } void visitArguments(ImmutableArray<IArgumentOperation> arguments) { if (arguments != null) { foreach (IArgumentOperation arg in arguments) { VerifySubTree(arg); } } } } private static void VisitLoop(ILoopOperation operation) { Assert.Equal(OperationKind.Loop, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ContinueLabel); Assert.NotNull(operation.ExitLabel); } public override void VisitLabeled(ILabeledOperation operation) { Assert.Equal(OperationKind.Labeled, operation.Kind); Assert.NotNull(operation.Label); if (operation.Operation == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Operation, operation.Children.Single()); } } public override void VisitBranch(IBranchOperation operation) { Assert.Equal(OperationKind.Branch, operation.Kind); Assert.NotNull(operation.Target); switch (operation.BranchKind) { case BranchKind.Break: case BranchKind.Continue: case BranchKind.GoTo: break; default: Assert.False(true); break; } Assert.Empty(operation.Children); } public override void VisitEmpty(IEmptyOperation operation) { Assert.Equal(OperationKind.Empty, operation.Kind); Assert.Empty(operation.Children); } public override void VisitReturn(IReturnOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Return, OperationKind.YieldReturn, OperationKind.YieldBreak }); if (operation.ReturnedValue == null) { Assert.NotEqual(OperationKind.YieldReturn, operation.Kind); Assert.Empty(operation.Children); } else { Assert.Same(operation.ReturnedValue, operation.Children.Single()); } } public override void VisitLock(ILockOperation operation) { Assert.Equal(OperationKind.Lock, operation.Kind); AssertEx.Equal(new[] { operation.LockedValue, operation.Body }, operation.Children); } public override void VisitTry(ITryOperation operation) { Assert.Equal(OperationKind.Try, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Body }; _ = operation.ExitLabel; children = children.Concat(operation.Catches); if (operation.Finally != null) { children = children.Concat(new[] { operation.Finally }); } AssertEx.Equal(children, operation.Children); } public override void VisitCatchClause(ICatchClauseOperation operation) { Assert.Equal(OperationKind.CatchClause, operation.Kind); var exceptionType = operation.ExceptionType; VisitLocals(operation.Locals); IEnumerable<IOperation> children = Array.Empty<IOperation>(); if (operation.ExceptionDeclarationOrExpression != null) { children = children.Concat(new[] { operation.ExceptionDeclarationOrExpression }); } if (operation.Filter != null) { children = children.Concat(new[] { operation.Filter }); } children = children.Concat(new[] { operation.Handler }); AssertEx.Equal(children, operation.Children); } public override void VisitUsing(IUsingOperation operation) { Assert.Equal(OperationKind.Using, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Resources, operation.Body }, operation.Children); Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind); Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind); _ = ((UsingOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } // https://github.com/dotnet/roslyn/issues/21281 internal override void VisitFixed(IFixedOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Variables, operation.Body }, operation.Children); } internal override void VisitAggregateQuery(IAggregateQueryOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Group, operation.Aggregation }, operation.Children); } public override void VisitExpressionStatement(IExpressionStatementOperation operation) { Assert.Equal(OperationKind.ExpressionStatement, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } internal override void VisitWithStatement(IWithStatementOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Body }, operation.Children); } public override void VisitStop(IStopOperation operation) { Assert.Equal(OperationKind.Stop, operation.Kind); Assert.Empty(operation.Children); } public override void VisitEnd(IEndOperation operation) { Assert.Equal(OperationKind.End, operation.Kind); Assert.Empty(operation.Children); } public override void VisitInvocation(IInvocationOperation operation) { Assert.Equal(OperationKind.Invocation, operation.Kind); Assert.NotNull(operation.TargetMethod); var isVirtual = operation.IsVirtual; IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(operation.Arguments); } else { children = operation.Arguments; } AssertEx.Equal(children, operation.Children); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.TargetMethod.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } public override void VisitArgument(IArgumentOperation operation) { Assert.Equal(OperationKind.Argument, operation.Kind); Assert.Contains(operation.ArgumentKind, new[] { ArgumentKind.DefaultValue, ArgumentKind.Explicit, ArgumentKind.ParamArray }); var parameter = operation.Parameter; Assert.Same(operation.Value, operation.Children.Single()); var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.ArgumentKind == ArgumentKind.DefaultValue) { Assert.True(operation.Descendants().All(n => n.IsImplicit), $"Explicit node in default argument value ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}"); } } public override void VisitOmittedArgument(IOmittedArgumentOperation operation) { Assert.Equal(OperationKind.OmittedArgument, operation.Kind); Assert.Empty(operation.Children); } public override void VisitArrayElementReference(IArrayElementReferenceOperation operation) { Assert.Equal(OperationKind.ArrayElementReference, operation.Kind); AssertEx.Equal(new[] { operation.ArrayReference }.Concat(operation.Indices), operation.Children); } internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Same(operation.Pointer, operation.Children.Single()); } public override void VisitLocalReference(ILocalReferenceOperation operation) { Assert.Equal(OperationKind.LocalReference, operation.Kind); Assert.NotNull(operation.Local); var isDeclaration = operation.IsDeclaration; Assert.Empty(operation.Children); } public override void VisitParameterReference(IParameterReferenceOperation operation) { Assert.Equal(OperationKind.ParameterReference, operation.Kind); Assert.NotNull(operation.Parameter); Assert.Empty(operation.Children); } public override void VisitInstanceReference(IInstanceReferenceOperation operation) { Assert.Equal(OperationKind.InstanceReference, operation.Kind); Assert.Empty(operation.Children); var referenceKind = operation.ReferenceKind; } private void VisitMemberReference(IMemberReferenceOperation operation) { VisitMemberReference(operation, Array.Empty<IOperation>()); } private void VisitMemberReference(IMemberReferenceOperation operation, IEnumerable<IOperation> additionalChildren) { Assert.NotNull(operation.Member); IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(additionalChildren); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.Member.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } else { children = additionalChildren; } AssertEx.Equal(children, operation.Children); } public override void VisitFieldReference(IFieldReferenceOperation operation) { Assert.Equal(OperationKind.FieldReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Field); var isDeclaration = operation.IsDeclaration; } public override void VisitMethodReference(IMethodReferenceOperation operation) { Assert.Equal(OperationKind.MethodReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Method); var isVirtual = operation.IsVirtual; } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { Assert.Equal(OperationKind.PropertyReference, operation.Kind); VisitMemberReference(operation, operation.Arguments); Assert.Same(operation.Member, operation.Property); } public override void VisitEventReference(IEventReferenceOperation operation) { Assert.Equal(OperationKind.EventReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Event); } public override void VisitEventAssignment(IEventAssignmentOperation operation) { Assert.Equal(OperationKind.EventAssignment, operation.Kind); var adds = operation.Adds; AssertEx.Equal(new[] { operation.EventReference, operation.HandlerValue }, operation.Children); } public override void VisitConditionalAccess(IConditionalAccessOperation operation) { Assert.Equal(OperationKind.ConditionalAccess, operation.Kind); Assert.NotNull(operation.Type); AssertEx.Equal(new[] { operation.Operation, operation.WhenNotNull }, operation.Children); } public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) { Assert.Equal(OperationKind.ConditionalAccessInstance, operation.Kind); Assert.Empty(operation.Children); } internal override void VisitPlaceholder(IPlaceholderOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Empty(operation.Children); } public override void VisitUnaryOperator(IUnaryOperation operation) { Assert.Equal(OperationKind.UnaryOperator, operation.Kind); Assert.Equal(OperationKind.Unary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitBinaryOperator(IBinaryOperation operation) { Assert.Equal(OperationKind.BinaryOperator, operation.Kind); Assert.Equal(OperationKind.Binary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod; var binaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; var isCompareText = operation.IsCompareText; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation) { Assert.Equal(OperationKind.TupleBinaryOperator, operation.Kind); Assert.Equal(OperationKind.TupleBinary, operation.Kind); var binaryOperationKind = operation.OperatorKind; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitConversion(IConversionOperation operation) { Assert.Equal(OperationKind.Conversion, operation.Kind); var operatorMethod = operation.OperatorMethod; var conversion = operation.Conversion; var isChecked = operation.IsChecked; var isTryCast = operation.IsTryCast; switch (operation.Language) { case LanguageNames.CSharp: CSharp.Conversion csharpConversion = CSharp.CSharpExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => VisualBasic.VisualBasicExtensions.GetConversion(operation)); break; case LanguageNames.VisualBasic: VisualBasic.Conversion visualBasicConversion = VisualBasic.VisualBasicExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => CSharp.CSharpExtensions.GetConversion(operation)); break; default: Debug.Fail($"Language {operation.Language} is unknown!"); break; } Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitConditional(IConditionalOperation operation) { Assert.Equal(OperationKind.Conditional, operation.Kind); bool isRef = operation.IsRef; if (operation.WhenFalse != null) { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue, operation.WhenFalse }, operation.Children); } else { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue }, operation.Children); } } public override void VisitCoalesce(ICoalesceOperation operation) { Assert.Equal(OperationKind.Coalesce, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.WhenNull }, operation.Children); var valueConversion = operation.ValueConversion; } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { Assert.Equal(OperationKind.CoalesceAssignment, operation.Kind); AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitIsType(IIsTypeOperation operation) { Assert.Equal(OperationKind.IsType, operation.Kind); Assert.NotNull(operation.TypeOperand); bool isNegated = operation.IsNegated; Assert.Same(operation.ValueOperand, operation.Children.Single()); } public override void VisitSizeOf(ISizeOfOperation operation) { Assert.Equal(OperationKind.SizeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitTypeOf(ITypeOfOperation operation) { Assert.Equal(OperationKind.TypeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.AnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Same(operation.Body, operation.Children.Single()); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.FlowAnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Empty(operation.Children); } public override void VisitLocalFunction(ILocalFunctionOperation operation) { Assert.Equal(OperationKind.LocalFunction, operation.Kind); Assert.NotNull(operation.Symbol); if (operation.Body != null) { var children = operation.Children.ToImmutableArray(); Assert.Same(operation.Body, children[0]); if (operation.IgnoredBody != null) { Assert.Same(operation.IgnoredBody, children[1]); Assert.Equal(2, children.Length); } else { Assert.Equal(1, children.Length); } } else { Assert.Null(operation.IgnoredBody); Assert.Empty(operation.Children); } } public override void VisitLiteral(ILiteralOperation operation) { Assert.Equal(OperationKind.Literal, operation.Kind); Assert.Empty(operation.Children); } public override void VisitAwait(IAwaitOperation operation) { Assert.Equal(OperationKind.Await, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitNameOf(INameOfOperation operation) { Assert.Equal(OperationKind.NameOf, operation.Kind); Assert.Same(operation.Argument, operation.Children.Single()); } public override void VisitThrow(IThrowOperation operation) { Assert.Equal(OperationKind.Throw, operation.Kind); if (operation.Exception == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Exception, operation.Children.Single()); } } public override void VisitAddressOf(IAddressOfOperation operation) { Assert.Equal(OperationKind.AddressOf, operation.Kind); Assert.Same(operation.Reference, operation.Children.Single()); } public override void VisitObjectCreation(IObjectCreationOperation operation) { Assert.Equal(OperationKind.ObjectCreation, operation.Kind); var constructor = operation.Constructor; // When parameter-less struct constructor is inaccessible, the constructor symbol is null if (!operation.Type.IsValueType) { Assert.NotNull(constructor); if (constructor == null) { Assert.Empty(operation.Arguments); } } IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) { Assert.Equal(OperationKind.AnonymousObjectCreation, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); foreach (var initializer in operation.Initializers) { var simpleAssignment = (ISimpleAssignmentOperation)initializer; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Assert.Empty(propertyReference.Arguments); Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind); Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind); } } public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) { Assert.Equal(OperationKind.DynamicObjectCreation, operation.Kind); IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitDynamicInvocation(IDynamicInvocationOperation operation) { Assert.Equal(OperationKind.DynamicInvocation, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) { Assert.Equal(OperationKind.DynamicIndexerAccess, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) { Assert.Equal(OperationKind.ObjectOrCollectionInitializer, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); } public override void VisitMemberInitializer(IMemberInitializerOperation operation) { Assert.Equal(OperationKind.MemberInitializer, operation.Kind); AssertEx.Equal(new[] { operation.InitializedMember, operation.Initializer }, operation.Children); } private void VisitSymbolInitializer(ISymbolInitializerOperation operation) { VisitLocals(operation.Locals); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitFieldInitializer(IFieldInitializerOperation operation) { Assert.Equal(OperationKind.FieldInitializer, operation.Kind); foreach (var field in operation.InitializedFields) { Assert.NotNull(field); } VisitSymbolInitializer(operation); } public override void VisitVariableInitializer(IVariableInitializerOperation operation) { Assert.Equal(OperationKind.VariableInitializer, operation.Kind); Assert.Empty(operation.Locals); VisitSymbolInitializer(operation); } public override void VisitPropertyInitializer(IPropertyInitializerOperation operation) { Assert.Equal(OperationKind.PropertyInitializer, operation.Kind); foreach (var property in operation.InitializedProperties) { Assert.NotNull(property); } VisitSymbolInitializer(operation); } public override void VisitParameterInitializer(IParameterInitializerOperation operation) { Assert.Equal(OperationKind.ParameterInitializer, operation.Kind); Assert.NotNull(operation.Parameter); VisitSymbolInitializer(operation); } public override void VisitArrayCreation(IArrayCreationOperation operation) { Assert.Equal(OperationKind.ArrayCreation, operation.Kind); IEnumerable<IOperation> children = operation.DimensionSizes; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitArrayInitializer(IArrayInitializerOperation operation) { Assert.Equal(OperationKind.ArrayInitializer, operation.Kind); Assert.Null(operation.Type); AssertEx.Equal(operation.ElementValues, operation.Children); } private void VisitAssignment(IAssignmentOperation operation) { AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { Assert.Equal(OperationKind.SimpleAssignment, operation.Kind); bool isRef = operation.IsRef; VisitAssignment(operation); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { Assert.Equal(OperationKind.CompoundAssignment, operation.Kind); var operatorMethod = operation.OperatorMethod; var binaryOperationKind = operation.OperatorKind; var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.Syntax.Language == LanguageNames.CSharp) { Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetOutConversion(operation)); var inConversionInternal = CSharp.CSharpExtensions.GetInConversion(operation); var outConversionInternal = CSharp.CSharpExtensions.GetOutConversion(operation); } else { Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetOutConversion(operation)); var inConversionInternal = VisualBasic.VisualBasicExtensions.GetInConversion(operation); var outConversionInternal = VisualBasic.VisualBasicExtensions.GetOutConversion(operation); } var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; VisitAssignment(operation); } public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Increment, OperationKind.Decrement }); var operatorMethod = operation.OperatorMethod; var isPostFix = operation.IsPostfix; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitParenthesized(IParenthesizedOperation operation) { Assert.Equal(OperationKind.Parenthesized, operation.Kind); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) { Assert.Equal(OperationKind.DynamicMemberReference, operation.Kind); Assert.NotNull(operation.MemberName); foreach (var typeArg in operation.TypeArguments) { Assert.NotNull(typeArg); } var containingType = operation.ContainingType; if (operation.Instance == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Instance, operation.Children.Single()); } } public override void VisitDefaultValue(IDefaultValueOperation operation) { Assert.Equal(OperationKind.DefaultValue, operation.Kind); Assert.Empty(operation.Children); } public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) { Assert.Equal(OperationKind.TypeParameterObjectCreation, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } public override void VisitInvalid(IInvalidOperation operation) { Assert.Equal(OperationKind.Invalid, operation.Kind); } public override void VisitTuple(ITupleOperation operation) { Assert.Equal(OperationKind.Tuple, operation.Kind); var naturalType = operation.NaturalType; AssertEx.Equal(operation.Elements, operation.Children); } public override void VisitInterpolatedString(IInterpolatedStringOperation operation) { Assert.Equal(OperationKind.InterpolatedString, operation.Kind); AssertEx.Equal(operation.Parts, operation.Children); } public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) { Assert.Equal(OperationKind.InterpolatedStringText, operation.Kind); if (operation.Text.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind); } Assert.Same(operation.Text, operation.Children.Single()); } public override void VisitInterpolation(IInterpolationOperation operation) { Assert.Equal(OperationKind.Interpolation, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Expression }; if (operation.Alignment != null) { children = children.Concat(new[] { operation.Alignment }); } if (operation.FormatString != null) { if (operation.FormatString.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind); } children = children.Concat(new[] { operation.FormatString }); } AssertEx.Equal(children, operation.Children); } private void VisitPatternCommon(IPatternOperation pattern) { Assert.NotNull(pattern.InputType); Assert.NotNull(pattern.NarrowedType); Assert.Null(pattern.Type); Assert.False(pattern.ConstantValue.HasValue); } public override void VisitConstantPattern(IConstantPatternOperation operation) { Assert.Equal(OperationKind.ConstantPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitRelationalPattern(IRelationalPatternOperation operation) { Assert.Equal(OperationKind.RelationalPattern, operation.Kind); Assert.True(operation.OperatorKind is Operations.BinaryOperatorKind.LessThan or Operations.BinaryOperatorKind.LessThanOrEqual or Operations.BinaryOperatorKind.GreaterThan or Operations.BinaryOperatorKind.GreaterThanOrEqual or Operations.BinaryOperatorKind.Equals or // Error cases Operations.BinaryOperatorKind.NotEquals); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitBinaryPattern(IBinaryPatternOperation operation) { Assert.Equal(OperationKind.BinaryPattern, operation.Kind); VisitPatternCommon(operation); Assert.True(operation.OperatorKind switch { Operations.BinaryOperatorKind.Or => true, Operations.BinaryOperatorKind.And => true, _ => false }); var children = operation.Children.ToArray(); Assert.Equal(2, children.Length); Assert.Same(operation.LeftPattern, children[0]); Assert.Same(operation.RightPattern, children[1]); } public override void VisitNegatedPattern(INegatedPatternOperation operation) { Assert.Equal(OperationKind.NegatedPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Pattern, operation.Children.Single()); } public override void VisitTypePattern(ITypePatternOperation operation) { Assert.Equal(OperationKind.TypePattern, operation.Kind); Assert.NotNull(operation.MatchedType); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { Assert.Equal(OperationKind.DeclarationPattern, operation.Kind); VisitPatternCommon(operation); if (operation.Syntax.IsKind(CSharp.SyntaxKind.VarPattern) || // in `var (x, y)`, the syntax here is the designation `x`. operation.Syntax.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.True(operation.MatchesNull); Assert.Null(operation.MatchedType); } else { Assert.False(operation.MatchesNull); Assert.NotNull(operation.MatchedType); } var designation = (operation.Syntax as CSharp.Syntax.DeclarationPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VarPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VariableDesignationSyntax); if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } Assert.Empty(operation.Children); } public override void VisitRecursivePattern(IRecursivePatternOperation operation) { Assert.Equal(OperationKind.RecursivePattern, operation.Kind); VisitPatternCommon(operation); Assert.NotNull(operation.MatchedType); switch (operation.DeconstructSymbol) { case IErrorTypeSymbol error: case null: // OK: indicates deconstruction of a tuple, or an error case break; case IMethodSymbol method: // when we have a method, it is a `Deconstruct` method Assert.Equal("Deconstruct", method.Name); break; case ITypeSymbol type: // when we have a type, it is the type "ITuple" Assert.Equal("ITuple", type.Name); break; default: Assert.True(false, $"Unexpected symbol {operation.DeconstructSymbol}"); break; } var designation = (operation.Syntax as CSharp.Syntax.RecursivePatternSyntax)?.Designation; if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } foreach (var subpat in operation.PropertySubpatterns) { Assert.True(subpat is IPropertySubpatternOperation); } IEnumerable<IOperation> children = operation.DeconstructionSubpatterns.Cast<IOperation>(); children = children.Concat(operation.PropertySubpatterns); AssertEx.Equal(children, operation.Children); } public override void VisitPropertySubpattern(IPropertySubpatternOperation operation) { Assert.NotNull(operation.Pattern); var children = new IOperation[] { operation.Member, operation.Pattern }; AssertEx.Equal(children, operation.Children); if (operation.Member.Kind == OperationKind.Invalid) { return; } Assert.True(operation.Member is IMemberReferenceOperation); var member = (IMemberReferenceOperation)operation.Member; switch (member.Member) { case IFieldSymbol field: case IPropertySymbol prop: break; case var symbol: Assert.True(false, $"Unexpected symbol {symbol}"); break; } } public override void VisitSwitchExpression(ISwitchExpressionOperation operation) { //force the existence of IsExhaustive _ = operation.IsExhaustive; Assert.NotNull(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.Equal(OperationKind.SwitchExpression, operation.Kind); Assert.NotNull(operation.Value); var children = operation.Arms.Cast<IOperation>().Prepend(operation.Value); AssertEx.Equal(children, operation.Children); } public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) { Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.NotNull(operation.Pattern); _ = operation.Guard; Assert.NotNull(operation.Value); VisitLocals(operation.Locals); var children = operation.Guard == null ? new[] { operation.Pattern, operation.Value } : new[] { operation.Pattern, operation.Guard, operation.Value }; AssertEx.Equal(children, operation.Children); } public override void VisitIsPattern(IIsPatternOperation operation) { Assert.Equal(OperationKind.IsPattern, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Pattern }, operation.Children); } public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Pattern, operation.CaseKind); Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label); if (operation.Guard != null) { AssertEx.Equal(new[] { operation.Pattern, operation.Guard }, operation.Children); } else { Assert.Same(operation.Pattern, operation.Children.Single()); } } public override void VisitTranslatedQuery(ITranslatedQueryOperation operation) { Assert.Equal(OperationKind.TranslatedQuery, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation) { Assert.Equal(OperationKind.DeclarationExpression, operation.Kind); Assert.Same(operation.Expression, operation.Children.Single()); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { Assert.Equal(OperationKind.DeconstructionAssignment, operation.Kind); VisitAssignment(operation); } public override void VisitDelegateCreation(IDelegateCreationOperation operation) { Assert.Equal(OperationKind.DelegateCreation, operation.Kind); Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitRaiseEvent(IRaiseEventOperation operation) { Assert.Equal(OperationKind.RaiseEvent, operation.Kind); AssertEx.Equal(new IOperation[] { operation.EventReference }.Concat(operation.Arguments), operation.Children); } public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Range, operation.CaseKind); AssertEx.Equal(new[] { operation.MinimumValue, operation.MaximumValue }, operation.Children); } public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation) { Assert.Equal(OperationKind.ConstructorBodyOperation, operation.Kind); Assert.Equal(OperationKind.ConstructorBody, operation.Kind); VisitLocals(operation.Locals); var builder = ArrayBuilder<IOperation>.GetInstance(); if (operation.Initializer != null) { builder.Add(operation.Initializer); } if (operation.BlockBody != null) { builder.Add(operation.BlockBody); } if (operation.ExpressionBody != null) { builder.Add(operation.ExpressionBody); } AssertEx.Equal(builder, operation.Children); builder.Free(); } public override void VisitMethodBodyOperation(IMethodBodyOperation operation) { Assert.Equal(OperationKind.MethodBodyOperation, operation.Kind); Assert.Equal(OperationKind.MethodBody, operation.Kind); if (operation.BlockBody != null) { if (operation.ExpressionBody != null) { AssertEx.Equal(new[] { operation.BlockBody, operation.ExpressionBody }, operation.Children); } else { Assert.Same(operation.BlockBody, operation.Children.Single()); } } else if (operation.ExpressionBody != null) { Assert.Same(operation.ExpressionBody, operation.Children.Single()); } else { Assert.Empty(operation.Children); } } public override void VisitDiscardOperation(IDiscardOperation operation) { Assert.Equal(OperationKind.Discard, operation.Kind); Assert.Empty(operation.Children); var discardSymbol = operation.DiscardSymbol; Assert.Equal(operation.Type, discardSymbol.Type); } public override void VisitDiscardPattern(IDiscardPatternOperation operation) { Assert.Equal(OperationKind.DiscardPattern, operation.Kind); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitFlowCapture(IFlowCaptureOperation operation) { Assert.Equal(OperationKind.FlowCapture, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Value, operation.Children.Single()); switch (operation.Value.Kind) { case OperationKind.Invalid: case OperationKind.None: case OperationKind.AnonymousFunction: case OperationKind.FlowCaptureReference: case OperationKind.DefaultValue: case OperationKind.FlowAnonymousFunction: // must be an error case like in Microsoft.CodeAnalysis.CSharp.UnitTests.ConditionalOperatorTests.TestBothUntyped unit-test break; case OperationKind.OmittedArgument: case OperationKind.DeclarationExpression: case OperationKind.Discard: Assert.False(true, $"A {operation.Value.Kind} node should not be spilled or captured."); break; default: // Only values can be spilled/captured if (!operation.Value.ConstantValue.HasValue || operation.Value.ConstantValue.Value != null) { Assert.NotNull(operation.Value.Type); } break; } } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { Assert.Equal(OperationKind.FlowCaptureReference, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitIsNull(IIsNullOperation operation) { Assert.Equal(OperationKind.IsNull, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitCaughtException(ICaughtExceptionOperation operation) { Assert.Equal(OperationKind.CaughtException, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) { Assert.Equal(OperationKind.StaticLocalInitializationSemaphore, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); Assert.NotNull(operation.Local); Assert.True(operation.Local.IsStatic); } public override void VisitRangeOperation(IRangeOperation operation) { Assert.Equal(OperationKind.Range, operation.Kind); IOperation[] children = operation.Children.ToArray(); int index = 0; if (operation.LeftOperand != null) { Assert.Same(operation.LeftOperand, children[index++]); } if (operation.RightOperand != null) { Assert.Same(operation.RightOperand, children[index++]); } Assert.Equal(index, children.Length); } public override void VisitReDim(IReDimOperation operation) { Assert.Equal(OperationKind.ReDim, operation.Kind); AssertEx.Equal(operation.Clauses, operation.Children); var preserve = operation.Preserve; } public override void VisitReDimClause(IReDimClauseOperation operation) { Assert.Equal(OperationKind.ReDimClause, operation.Kind); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.DimensionSizes), operation.Children); } public override void VisitUsingDeclaration(IUsingDeclarationOperation operation) { Assert.NotNull(operation.DeclarationGroup); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.DeclarationGroup), operation.Children); Assert.True(operation.DeclarationGroup.IsImplicit); Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); _ = operation.IsAsynchronous; _ = operation.IsImplicit; _ = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } public override void VisitWith(IWithOperation operation) { Assert.Equal(OperationKind.With, operation.Kind); _ = operation.CloneMethod; IEnumerable<IOperation> children = SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.Initializer); AssertEx.Equal(children, operation.Children); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Compilers/Core/Portable/PEWriter/MethodSpecComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MethodSpecComparer : IEqualityComparer<IGenericMethodInstanceReference> { private readonly MetadataWriter _metadataWriter; internal MethodSpecComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(IGenericMethodInstanceReference? x, IGenericMethodInstanceReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); return _metadataWriter.GetMethodDefinitionOrReferenceHandle(x.GetGenericMethod(_metadataWriter.Context)) == _metadataWriter.GetMethodDefinitionOrReferenceHandle(y.GetGenericMethod(_metadataWriter.Context)) && _metadataWriter.GetMethodSpecificationSignatureHandle(x) == _metadataWriter.GetMethodSpecificationSignatureHandle(y); } public int GetHashCode(IGenericMethodInstanceReference methodInstanceReference) { return Hash.Combine( _metadataWriter.GetMethodDefinitionOrReferenceHandle(methodInstanceReference.GetGenericMethod(_metadataWriter.Context)).GetHashCode(), _metadataWriter.GetMethodSpecificationSignatureHandle(methodInstanceReference).GetHashCode()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MethodSpecComparer : IEqualityComparer<IGenericMethodInstanceReference> { private readonly MetadataWriter _metadataWriter; internal MethodSpecComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(IGenericMethodInstanceReference? x, IGenericMethodInstanceReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); return _metadataWriter.GetMethodDefinitionOrReferenceHandle(x.GetGenericMethod(_metadataWriter.Context)) == _metadataWriter.GetMethodDefinitionOrReferenceHandle(y.GetGenericMethod(_metadataWriter.Context)) && _metadataWriter.GetMethodSpecificationSignatureHandle(x) == _metadataWriter.GetMethodSpecificationSignatureHandle(y); } public int GetHashCode(IGenericMethodInstanceReference methodInstanceReference) { return Hash.Combine( _metadataWriter.GetMethodDefinitionOrReferenceHandle(methodInstanceReference.GetGenericMethod(_metadataWriter.Context)).GetHashCode(), _metadataWriter.GetMethodSpecificationSignatureHandle(methodInstanceReference).GetHashCode()); } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf { /// <summary> /// Finds code like typeof(someType).Name and determines whether it can be changed to nameof(someType), if yes then it offers a diagnostic /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpConvertTypeOfToNameOfDiagnosticAnalyzer : AbstractConvertTypeOfToNameOfDiagnosticAnalyzer { private static readonly string s_title = CSharpAnalyzersResources.typeof_can_be_converted__to_nameof; public CSharpConvertTypeOfToNameOfDiagnosticAnalyzer() : base(s_title, LanguageNames.CSharp) { } protected override bool IsValidTypeofAction(OperationAnalysisContext context) { var node = context.Operation.Syntax; var syntaxTree = node.SyntaxTree; // nameof was added in CSharp 6.0, so don't offer it for any languages before that time if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp6) { return false; } // Make sure that the syntax that we're looking at is actually a typeof expression and that // the parent syntax is a member access expression otherwise the syntax is not the kind of // expression that we want to analyze return node is TypeOfExpressionSyntax { Parent: MemberAccessExpressionSyntax } typeofExpression && // nameof(System.Void) isn't allowed in C#. typeofExpression is not { Type: PredefinedTypeSyntax { Keyword: { RawKind: (int)SyntaxKind.VoidKeyword } } }; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf { /// <summary> /// Finds code like typeof(someType).Name and determines whether it can be changed to nameof(someType), if yes then it offers a diagnostic /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpConvertTypeOfToNameOfDiagnosticAnalyzer : AbstractConvertTypeOfToNameOfDiagnosticAnalyzer { private static readonly string s_title = CSharpAnalyzersResources.typeof_can_be_converted__to_nameof; public CSharpConvertTypeOfToNameOfDiagnosticAnalyzer() : base(s_title, LanguageNames.CSharp) { } protected override bool IsValidTypeofAction(OperationAnalysisContext context) { var node = context.Operation.Syntax; var syntaxTree = node.SyntaxTree; // nameof was added in CSharp 6.0, so don't offer it for any languages before that time if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp6) { return false; } // Make sure that the syntax that we're looking at is actually a typeof expression and that // the parent syntax is a member access expression otherwise the syntax is not the kind of // expression that we want to analyze return node is TypeOfExpressionSyntax { Parent: MemberAccessExpressionSyntax } typeofExpression && // nameof(System.Void) isn't allowed in C#. typeofExpression is not { Type: PredefinedTypeSyntax { Keyword: { RawKind: (int)SyntaxKind.VoidKeyword } } }; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReaders.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct AssemblyReaders { public readonly MetadataReader MetadataReader; public readonly object SymReader; public AssemblyReaders(MetadataReader metadataReader, object symReader) { MetadataReader = metadataReader; SymReader = symReader; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct AssemblyReaders { public readonly MetadataReader MetadataReader; public readonly object SymReader; public AssemblyReaders(MetadataReader metadataReader, object symReader) { MetadataReader = metadataReader; SymReader = symReader; } } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/AscendingKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AscendingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AscendingKeywordRecommender() : base(SyntaxKind.AscendingKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.TargetToken.IsOrderByDirectionContext(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AscendingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AscendingKeywordRecommender() : base(SyntaxKind.AscendingKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.TargetToken.IsOrderByDirectionContext(); } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/EditorFeatures/CSharpTest/PullMemberUp/CSharpPullMemberUpTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp { public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); #region Quick Action private async Task TestQuickActionNotProvidedAsync( string initialMarkup, TestParameters parameters = default) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); if (actions.Length == 1) { // The dialog shows up, not quick action Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type); } else if (actions.Length > 1) { Assert.True(false, "Pull Members Up is provided via quick action"); } else { Assert.True(true); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface ITestInterface { } public class TestClass : ITestInterface { public int yo[||]u = 10086; } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() { var methodTest = @" namespace PushUpTest { public interface ITestInterface { void TestMethod(); } public class TestClass : ITestInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() { var propertyTest1 = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() { var input = @" namespace PushUpTest { public interface ITestInterface { void Foobar(); } public class TestClass : ITestInterface { public class N[||]estedClass { } } }"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAbstractMethodToInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface IInterface { } public abstract class TestClass : IInterface { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public interface IInterface { void TestMethod(); } public abstract class TestClass : IInterface { public abstract void TestMethod(); } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { public interface IInterface { } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public interface IInterface { void TestMethod<T>() where T : IDisposable; } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullSingleEventToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Event2, Event3; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestProperty { get; private set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestProperty[||]{ private get; set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } public class TestClass : IInterface { public int TestProperty{ private get; set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } interface FooInterface : IInterface { int TestPr[||]operty { set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } interface FooInterface : IInterface { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { set => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { set; } } public class TestClass : IInterface { private int j; public int this[int i] { set => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { get => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { get; } } public class TestClass : IInterface { private int j; public int this[int i] { get => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Endpoint { get; set; } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { bool TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Test[||]Method() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri TestMethod() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { bool TestMethod(Uri endpoint); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { event EventHandler TestEvent; } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler TestEvent { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Property { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestProperty { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return 5; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { public int TestMethod() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System.Linq; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System; using System.Linq; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Linq; // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; // blah blah public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using System.Linq; public class Base { public int TestMethod() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { public Foo Test[||]Method() { return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; using A_TestNs2; public class Base { public Uri Endpoint{ get; set; } public Foo TestMethod() { return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { public Foo Test[||]Method() { var uri = new Uri(""http://localhost""); return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using A_TestNs2; namespace TestNs1 { public class Base { public Foo TestMethod() { var uri = new Uri(""http://localhost""); return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs2; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs3; using TestNs4; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { public void Test[||]Method() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; using Sys = System; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using Enumer = System.Linq.Enumerable; public class Base { public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point{ get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" namespace TestNs1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { namespace InnerNs1 { using System; public class Base { public Uri Endpoint { get; set; } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { public int Test[||]Method() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; var expected = @" namespace TestNs1 { namespace InnerNs1 { using System; using System.Linq; using TestNs2.InnerNs2; public class Base { public Uri Endpoint { get; set; } public int TestMethod() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B { class Base { public Other GetOther() => null; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B; class Base { } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B; class Base { public Other GetOther() => null; } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { } class Other { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public int Get[||]Five() => 5; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { public int GetFive() => 5; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return 5; } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { public int TestMethod() { return 5; } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 using System; // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 using System; using System.Linq; // comment 3 public class Base { public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public var en[||]dpoint = new Uri(""http://localhost""); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public var endpoint = new Uri(""http://localhost""); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public var ran[||]ge = Enumerable.Range(0, 5); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public var range = Enumerable.Range(0, 5); } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() { var methodTest = @" namespace PushUpTest { public class Base { public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() { var propertyTest = @" using System; namespace PushUpTest { public class Base { public virtual int TestProperty { get => 111; private set; } } public class TestClass : Base { public override int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { public class Base2 { protected virtual event EventHandler Event3 { add { System.Console.WriteLine(""Hello""); } remove { System.Console.WriteLine(""World""); } }; } public class TestClass2 : Base2 { protected override event EventHandler E[||]vent3 { add { System.Console.WriteLine(""foo""); } remove { System.Console.WriteLine(""bar""); } }; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() { // Fields share the same name will be thought as 'override', since it will cause error // if two same name fields exist in one class var fieldTest = @" namespace PushUpTest { public class Base { public int you = -100000; } public class TestClass : Base { public int y[||]ou = 10086; } }"; await TestQuickActionNotProvidedAsync(fieldTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodToOrdinaryClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public class Base { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you[||]= 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int you = 10086; } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public class BaseClass { public void TestMethod<T>() where T : IDisposable { } } public class TestClass : BaseClass { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd = 4000, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and = 4000; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class Testclass2 : Base2 { private static event EventHandler Event1, Event4; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithBodyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base { } public class TestClass : Base { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { public class Base { public int TestProperty { get; private set; } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { private int j; public int th[||]is[int i] { get => j; set => j = value; } } }"; var expected = @" namespace PushUpTest { public class Base { public int this[int i] { get => j; set => j = value; } } public class TestClass : Base { private int j; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int BarBar(); } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int F[||]oo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Foo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int Foo { get; set; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j, [||]k = 10; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { private int k = 10; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBClassViaQuickAction() { // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in // AbstractCodeGenerationService will return null. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> public class TestClass : VBInterface { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int fo[||]obar = 0; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int foo[||]bar { get; set; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() { var input = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public int foo[||]bar { get; set; } } </Document> </Project> <Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { public Goo Ge[||]tGoo() { return new Goo(String.Empty); } } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using N2; using System; namespace N1 { public class Base { public Goo GetGoo() { return new Goo(String.Empty); } } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); } #endregion Quick Action #region Dialog internal Task TestWithPullMemberDialogAsync( string initialMarkUp, string expectedResult, IEnumerable<(string name, bool makeAbstract)> selection = null, string destinationName = null, int index = 0, TestParameters parameters = default) { var service = new TestPullMemberUpService(selection, destinationName); return TestInRegularAndScript1Async( initialMarkUp, expectedResult, index, parameters.WithFixProviderData(service)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { partial void Bar[||]Bar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { void BarBar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { public partial void Bar[||]Bar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { public partial void BarBar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } protected void F[||]oo(int i) { // do awesome things } private static string Bar(string x) {} } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { string Bar(string x); void Foo(int i); void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } public void Foo(int i) { // do awesome things } public string Bar(string x) {} } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicEventsToInterface() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; event EventHandler Event2; event EventHandler Event3; } public class TestClass : IInterface { public event EventHandler Event1; public event EventHandler Event2; public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodToInnerInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { private void Bar[||]Bar() { } interface IInterface { } } }"; var expected = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { public void BarBar() { } interface IInterface { void BarBar(); } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public class TestClass : IInterface { public int th[||]is[int i] { get => j = value; } private static void BarBar() {} protected static event EventHandler event1, event2; internal static int Foo { get; set; } } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { int this[int i] { get; } int Foo { get; set; } event EventHandler event1; event EventHandler event2; void BarBar(); } public class TestClass : IInterface { public int this[int i] { get => j = value; } public void BarBar() {} public event EventHandler event1; public event EventHandler event2; public int Foo { get; set; } } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAsyncMethod() { var testText = @" using System.Threading.Tasks; internal interface IPullUp { } internal class PullUp : IPullUp { internal async Task PullU[||]pAsync() { await Task.Delay(1000); } }"; var expectedText = @" using System.Threading.Tasks; internal interface IPullUp { Task PullUpAsync(); } internal class PullUp : IPullUp { public async Task PullUpAsync() { await Task.Delay(1000); } }"; await TestWithPullMemberDialogAsync(testText, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodWithAbstractOptionToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractMethodToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public abstract class TestClass : Base { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public abstract class TestClass : Base { } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleEventsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event1; private static event EventHandler Event3; private static event EventHandler Event4; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleAbstractEventsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class Testclass2 : ITest { protected abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event1; event EventHandler Event3; event EventHandler Event4; } public abstract class Testclass2 : ITest { public abstract event EventHandler Event1; public abstract event EventHandler Event3; public abstract event EventHandler Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractEventToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private static abstract event EventHandler Event3; } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public class Testclass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullSingleNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class TestClass2 : ITest { protected event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public abstract class TestClass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullFieldsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { public int i, [||]j = 10, k = 100; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { public int i; public int j = 10; public int k = 100; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property => 2.717; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; } } public class Testclass2 : ITest { public readonly double TestProperty => 2.717; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property { get; set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; set; } } public class Testclass2 : ITest { public double TestProperty { get; set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private static double Test[||]Property { set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { set; } } public class Testclass2 : ITest { public double Test[||]Property { set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" abstract class B { } class D : B { int [||]X => 7; }"; var expected = @" abstract class B { private abstract int X { get; } } class D : B { override int X => 7; }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private abstract event EventHandler Event3; } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { public abstract class BaseClass { public abstract event EventHandler Event1; } public class TestClass : BaseClass { public override event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1); } #endregion Dialog #region Selections and caret position [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestArgsIsPartOfHeader() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [Test2] void C([||]) { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretBeforeAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [||][Test] [Test2] void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [|void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test] void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes3() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test][| void C() { } |] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [[||]Test] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test] [Test2]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [[||]Test] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributeLists() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test]|] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] // Comment1 [Test2] // Comment2 [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] // Comment1 [Test2] // Comment2 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLoc1() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [||]void C() { } } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelection() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [| // Comment1 void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { // Comment1 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments2() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|/// <summary> /// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments3() { var testText = @" namespace PushUpTest { public class A { } public class B : A { /// <summary> [|/// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp { public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); #region Quick Action private async Task TestQuickActionNotProvidedAsync( string initialMarkup, TestParameters parameters = default) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); if (actions.Length == 1) { // The dialog shows up, not quick action Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type); } else if (actions.Length > 1) { Assert.True(false, "Pull Members Up is provided via quick action"); } else { Assert.True(true); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface ITestInterface { } public class TestClass : ITestInterface { public int yo[||]u = 10086; } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() { var methodTest = @" namespace PushUpTest { public interface ITestInterface { void TestMethod(); } public class TestClass : ITestInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() { var propertyTest1 = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() { var input = @" namespace PushUpTest { public interface ITestInterface { void Foobar(); } public class TestClass : ITestInterface { public class N[||]estedClass { } } }"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAbstractMethodToInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface IInterface { } public abstract class TestClass : IInterface { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public interface IInterface { void TestMethod(); } public abstract class TestClass : IInterface { public abstract void TestMethod(); } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { public interface IInterface { } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public interface IInterface { void TestMethod<T>() where T : IDisposable; } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullSingleEventToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Event2, Event3; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestProperty { get; private set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestProperty[||]{ private get; set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } public class TestClass : IInterface { public int TestProperty{ private get; set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } interface FooInterface : IInterface { int TestPr[||]operty { set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } interface FooInterface : IInterface { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { set => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { set; } } public class TestClass : IInterface { private int j; public int this[int i] { set => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { get => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { get; } } public class TestClass : IInterface { private int j; public int this[int i] { get => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Endpoint { get; set; } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { bool TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Test[||]Method() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri TestMethod() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { bool TestMethod(Uri endpoint); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { event EventHandler TestEvent; } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler TestEvent { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Property { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestProperty { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return 5; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { public int TestMethod() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System.Linq; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System; using System.Linq; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Linq; // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; // blah blah public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using System.Linq; public class Base { public int TestMethod() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { public Foo Test[||]Method() { return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; using A_TestNs2; public class Base { public Uri Endpoint{ get; set; } public Foo TestMethod() { return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { public Foo Test[||]Method() { var uri = new Uri(""http://localhost""); return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using A_TestNs2; namespace TestNs1 { public class Base { public Foo TestMethod() { var uri = new Uri(""http://localhost""); return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs2; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs3; using TestNs4; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { public void Test[||]Method() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; using Sys = System; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using Enumer = System.Linq.Enumerable; public class Base { public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point{ get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" namespace TestNs1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { namespace InnerNs1 { using System; public class Base { public Uri Endpoint { get; set; } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { public int Test[||]Method() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; var expected = @" namespace TestNs1 { namespace InnerNs1 { using System; using System.Linq; using TestNs2.InnerNs2; public class Base { public Uri Endpoint { get; set; } public int TestMethod() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B { class Base { public Other GetOther() => null; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B; class Base { } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B; class Base { public Other GetOther() => null; } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { } class Other { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public int Get[||]Five() => 5; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { public int GetFive() => 5; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return 5; } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { public int TestMethod() { return 5; } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 using System; // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 using System; using System.Linq; // comment 3 public class Base { public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public var en[||]dpoint = new Uri(""http://localhost""); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public var endpoint = new Uri(""http://localhost""); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public var ran[||]ge = Enumerable.Range(0, 5); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public var range = Enumerable.Range(0, 5); } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() { var methodTest = @" namespace PushUpTest { public class Base { public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() { var propertyTest = @" using System; namespace PushUpTest { public class Base { public virtual int TestProperty { get => 111; private set; } } public class TestClass : Base { public override int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { public class Base2 { protected virtual event EventHandler Event3 { add { System.Console.WriteLine(""Hello""); } remove { System.Console.WriteLine(""World""); } }; } public class TestClass2 : Base2 { protected override event EventHandler E[||]vent3 { add { System.Console.WriteLine(""foo""); } remove { System.Console.WriteLine(""bar""); } }; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() { // Fields share the same name will be thought as 'override', since it will cause error // if two same name fields exist in one class var fieldTest = @" namespace PushUpTest { public class Base { public int you = -100000; } public class TestClass : Base { public int y[||]ou = 10086; } }"; await TestQuickActionNotProvidedAsync(fieldTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodToOrdinaryClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public class Base { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you[||]= 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int you = 10086; } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public class BaseClass { public void TestMethod<T>() where T : IDisposable { } } public class TestClass : BaseClass { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd = 4000, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and = 4000; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class Testclass2 : Base2 { private static event EventHandler Event1, Event4; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithBodyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base { } public class TestClass : Base { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { public class Base { public int TestProperty { get; private set; } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { private int j; public int th[||]is[int i] { get => j; set => j = value; } } }"; var expected = @" namespace PushUpTest { public class Base { public int this[int i] { get => j; set => j = value; } } public class TestClass : Base { private int j; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int BarBar(); } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int F[||]oo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Foo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int Foo { get; set; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j, [||]k = 10; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { private int k = 10; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBClassViaQuickAction() { // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in // AbstractCodeGenerationService will return null. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> public class TestClass : VBInterface { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int fo[||]obar = 0; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int foo[||]bar { get; set; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() { var input = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public int foo[||]bar { get; set; } } </Document> </Project> <Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { public Goo Ge[||]tGoo() { return new Goo(String.Empty); } } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using N2; using System; namespace N1 { public class Base { public Goo GetGoo() { return new Goo(String.Empty); } } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); } #endregion Quick Action #region Dialog internal Task TestWithPullMemberDialogAsync( string initialMarkUp, string expectedResult, IEnumerable<(string name, bool makeAbstract)> selection = null, string destinationName = null, int index = 0, TestParameters parameters = default) { var service = new TestPullMemberUpService(selection, destinationName); return TestInRegularAndScript1Async( initialMarkUp, expectedResult, index, parameters.WithFixProviderData(service)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { partial void Bar[||]Bar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { void BarBar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { public partial void Bar[||]Bar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { public partial void BarBar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } protected void F[||]oo(int i) { // do awesome things } private static string Bar(string x) {} } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { string Bar(string x); void Foo(int i); void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } public void Foo(int i) { // do awesome things } public string Bar(string x) {} } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicEventsToInterface() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; event EventHandler Event2; event EventHandler Event3; } public class TestClass : IInterface { public event EventHandler Event1; public event EventHandler Event2; public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodToInnerInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { private void Bar[||]Bar() { } interface IInterface { } } }"; var expected = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { public void BarBar() { } interface IInterface { void BarBar(); } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public class TestClass : IInterface { public int th[||]is[int i] { get => j = value; } private static void BarBar() {} protected static event EventHandler event1, event2; internal static int Foo { get; set; } } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { int this[int i] { get; } int Foo { get; set; } event EventHandler event1; event EventHandler event2; void BarBar(); } public class TestClass : IInterface { public int this[int i] { get => j = value; } public void BarBar() {} public event EventHandler event1; public event EventHandler event2; public int Foo { get; set; } } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAsyncMethod() { var testText = @" using System.Threading.Tasks; internal interface IPullUp { } internal class PullUp : IPullUp { internal async Task PullU[||]pAsync() { await Task.Delay(1000); } }"; var expectedText = @" using System.Threading.Tasks; internal interface IPullUp { Task PullUpAsync(); } internal class PullUp : IPullUp { public async Task PullUpAsync() { await Task.Delay(1000); } }"; await TestWithPullMemberDialogAsync(testText, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodWithAbstractOptionToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractMethodToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public abstract class TestClass : Base { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public abstract class TestClass : Base { } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleEventsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event1; private static event EventHandler Event3; private static event EventHandler Event4; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleAbstractEventsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class Testclass2 : ITest { protected abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event1; event EventHandler Event3; event EventHandler Event4; } public abstract class Testclass2 : ITest { public abstract event EventHandler Event1; public abstract event EventHandler Event3; public abstract event EventHandler Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractEventToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private static abstract event EventHandler Event3; } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public class Testclass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullSingleNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class TestClass2 : ITest { protected event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public abstract class TestClass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullFieldsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { public int i, [||]j = 10, k = 100; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { public int i; public int j = 10; public int k = 100; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property => 2.717; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; } } public class Testclass2 : ITest { public readonly double TestProperty => 2.717; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property { get; set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; set; } } public class Testclass2 : ITest { public double TestProperty { get; set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private static double Test[||]Property { set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { set; } } public class Testclass2 : ITest { public double Test[||]Property { set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" abstract class B { } class D : B { int [||]X => 7; }"; var expected = @" abstract class B { private abstract int X { get; } } class D : B { override int X => 7; }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private abstract event EventHandler Event3; } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { public abstract class BaseClass { public abstract event EventHandler Event1; } public class TestClass : BaseClass { public override event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1); } #endregion Dialog #region Selections and caret position [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestArgsIsPartOfHeader() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [Test2] void C([||]) { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretBeforeAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [||][Test] [Test2] void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [|void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test] void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes3() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test][| void C() { } |] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [[||]Test] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test] [Test2]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [[||]Test] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributeLists() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test]|] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] // Comment1 [Test2] // Comment2 [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] // Comment1 [Test2] // Comment2 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLoc1() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [||]void C() { } } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelection() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [| // Comment1 void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { // Comment1 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments2() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|/// <summary> /// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments3() { var testText = @" namespace PushUpTest { public class A { } public class B : A { /// <summary> [|/// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } #endregion } }
-1
dotnet/roslyn
56,341
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups
Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
cston
"2021-09-11T23:27:47Z"
"2021-09-22T23:13:46Z"
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
7cce6c7db26cd0a51e8b8c6126d9abaab11fb2eb
Avoid several breaking changes in overload resolution from inferred types of lambda expressions and method groups. Update "[better function member](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-function-member)" to prefer members where none of the conversions and none of the type arguments involved inferred types from lambda expressions or method groups. > #### Better function member > ... > Given an argument list `A` with a set of argument expressions `{E1, E2, ..., En}` and two applicable function members `Mp` and `Mq` with parameter types `{P1, P2, ..., Pn}` and `{Q1, Q2, ..., Qn}`, `Mp` is defined to be a ***better function member*** than `Mq` if > > 1. **for each argument, the implicit conversion from `Ex` to `Px` is not a _function_type_conversion_, and** > * **`Mp` is a non-generic method or `Mp` is a generic method with type parameters `{X1, X2, ..., Xp}` and for each type parameter `Xi` the type argument is inferred from an expression or from a type other than a _function_type_, and** > * **for at least one argument, the implicit conversion from `Ex` to `Qx` is a _function_type_conversion_, or `Mq` is a generic method with type parameters `{Y1, Y2, ..., Yq}` and for at least one type parameter `Yi` the type argument is inferred from a _function_type_, or** > 2. for each argument, the implicit conversion from `Ex` to `Qx` is not better than the implicit conversion from `Ex` to `Px`, and for at least one argument, the conversion from `Ex` to `Px` is better than the conversion from `Ex` to `Qx`. Update "[better conversion from expression](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#better-conversion-from-expression)" to prefer conversions that did not involve inferred types from lambda expressions or method groups. > #### Better conversion from expression > > Given an implicit conversion `C1` that converts from an expression `E` to a type `T1`, and an implicit conversion `C2` that converts from an expression `E` to a type `T2`, `C1` is a ***better conversion*** than `C2` if: > 1. **`C1` is not a _function_type_conversion_ and `C2` is a _function_type_conversion_, or** > 2. `E` is a non-constant _interpolated\_string\_expression_, `C1` is an _implicit\_string\_handler\_conversion_, `T1` is an _applicable\_interpolated\_string\_handler\_type_, and `C2` is not an _implicit\_string\_handler\_conversion_, or > 3. `E` does not exactly match `T2` and at least one of the following holds: > * `E` exactly matches `T1` ([Exactly matching Expression](../../spec/expressions.md#exactly-matching-expression)) > * `T1` is a better conversion target than `T2` ([Better conversion target](../../spec/expressions.md#better-conversion-target)) The changes resolve several breaking changes between C#9 and C#10. Fixes #55691 Fixes #56167 Fixes #56319 Relates to test plan #52192
./src/EditorFeatures/Core/Options/BraceCompletionOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Options { internal static class BraceCompletionOptions { // This is serialized by the Visual Studio-specific LanguageSettingsPersister public static readonly PerLanguageOption<bool> Enable = new(nameof(BraceCompletionOptions), nameof(Enable), defaultValue: true); } [ExportOptionProvider, Shared] internal class BraceCompletionOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public BraceCompletionOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( BraceCompletionOptions.Enable); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Options { internal static class BraceCompletionOptions { // This is serialized by the Visual Studio-specific LanguageSettingsPersister public static readonly PerLanguageOption<bool> Enable = new(nameof(BraceCompletionOptions), nameof(Enable), defaultValue: true); } [ExportOptionProvider, Shared] internal class BraceCompletionOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public BraceCompletionOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( BraceCompletionOptions.Enable); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; 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 { private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(); var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node); ConstantValue? resultConstant = null; bool isResultConstant = true; if (node.Contents.Count == 0) { resultConstant = ConstantValue.Create(string.Empty); } else { var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); foreach (var content in node.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue); // We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering, // when we perform overload resolution, to report a problem. So we do that check by calling // GenerateConversionForAssignment with objectType. However we want to preserve the original expression's // natural type so that overload resolution may select a specialized implementation of string.Format, // so we discard the result of that call and only preserve its diagnostics. BoundExpression? alignment = null; BoundLiteral? format = null; if (interpolation.AlignmentClause != null) { alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics); var alignmentConstant = alignment.ConstantValue; if (alignmentConstant != null && !alignmentConstant.IsBad) { const int magnitudeLimit = 32767; // check that the magnitude of the alignment is "in range". int alignmentValue = alignmentConstant.Int32Value; // We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value. alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue; if (alignmentValue < -magnitudeLimit) { diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit); } } else if (!alignment.HasErrors) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location); } } if (interpolation.FormatClause != null) { var text = interpolation.FormatClause.FormatStringToken.ValueText; char lastChar; bool hasErrors = false; if (text.Length == 0) { diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar)) { diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors); } builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false)); if (!isResultConstant || value.ConstantValue == null || !(interpolation is { FormatClause: null, AlignmentClause: null }) || !(value.ConstantValue is { IsString: true, IsBad: false })) { isResultConstant = false; continue; } resultConstant = (resultConstant is null) ? value.ConstantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue); continue; } case SyntaxKind.InterpolatedStringText: { var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText; builder.Add(new BoundLiteral(content, ConstantValue.Create(text, SpecialType.System_String), stringType)); if (isResultConstant) { var constantVal = ConstantValue.Create(ConstantValueUtils.UnescapeInterpolatedStringLiteral(text), SpecialType.System_String); resultConstant = (resultConstant is null) ? constantVal : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantVal); } continue; } default: throw ExceptionUtilities.UnexpectedValue(content.Kind()); } } if (!isResultConstant) { resultConstant = null; } } Debug.Assert(isResultConstant == (resultConstant != null)); return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType); } private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { // We have 4 possible lowering strategies, dependent on the contents of the string, in this order: // 1. The string is a constant value. We can just use the final value. // 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a // params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and // make no intermediate allocations. // 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression. // The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any // awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation // hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for // the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected. // We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we // cannot put a try/finally inside a filter block. // 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single // call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this // call will need to allocate a param array. // 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await // expression. This is turned into a call to string.Format. // // We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being // able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering. if (unconvertedInterpolatedString.ConstantValue is not null) { // Case 1 Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String })); return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } // Case 2. Attempt to see if all parts are strings. if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts)) { return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } if (tryBindAsHandlerType(out var result)) { // Case 3 return result; } // The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible // object. return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) => new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result) { result = null; if (InExpressionTree || !ValidateInterpolatedStringParts(unconvertedInterpolatedString)) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType is MissingMetadataTypeSymbol) { return false; } result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false); return true; } } private static bool ValidateInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString) => !unconvertedInterpolatedString.Parts.ContainsAwaitExpression() && unconvertedInterpolatedString.Parts.All(p => p is not BoundStringInsert { Value.Type.TypeKind: TypeKind.Dynamic }); private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray<BoundExpression> parts) => parts.All(p => p is BoundLiteral or BoundStringInsert { Value.Type.SpecialType: SpecialType.System_String, Alignment: null, Format: null }); private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator) { // Much like BindUnconvertedInterpolatedStringToString above, we only want to use DefaultInterpolatedStringHandler if it's worth it. We therefore // check for cases 1 and 2: if they are present, we let normal string binary operator binding machinery handle it. Otherwise, we take care of it ourselves. Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); convertedBinaryOperator = null; if (InExpressionTree) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType.IsErrorType()) { // Can't ever bind to the handler no matter what, so just let the default handling take care of it. Cases 4 and 5 are covered by this. return false; } bool isConstant = true; var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); int partsCount = 0; BoundBinaryOperator? current = binaryOperator; while (current != null) { Debug.Assert(current.IsUnconvertedInterpolatedStringAddition); stack.Push(current); isConstant = isConstant && current.Right.ConstantValue is not null; var rightInterpolatedString = (BoundUnconvertedInterpolatedString)current.Right; if (!ValidateInterpolatedStringParts(rightInterpolatedString)) { // Exception to case 3. Delegate to standard binding. stack.Free(); partsArrayBuilder.Free(); return false; } partsCount += rightInterpolatedString.Parts.Length; partsArrayBuilder.Add(rightInterpolatedString.Parts); switch (current.Left) { case BoundBinaryOperator leftOperator: current = leftOperator; continue; case BoundUnconvertedInterpolatedString interpolatedString: isConstant = isConstant && interpolatedString.ConstantValue is not null; if (!ValidateInterpolatedStringParts(interpolatedString)) { // Exception to case 3. Delegate to standard binding. stack.Free(); partsArrayBuilder.Free(); return false; } partsCount += interpolatedString.Parts.Length; partsArrayBuilder.Add(interpolatedString.Parts); current = null; break; default: throw ExceptionUtilities.UnexpectedValue(current.Left.Kind); } } Debug.Assert(partsArrayBuilder.Count == stack.Count + 1); Debug.Assert(partsArrayBuilder.Count >= 2); if (isConstant || (partsCount <= 4 && partsArrayBuilder.All(static parts => AllInterpolatedStringPartsAreStrings(parts)))) { // This is case 1 and 2. Let the standard machinery handle it stack.Free(); partsArrayBuilder.Free(); return false; } // Parts were added to the array from right to left, but lexical order is left to right. partsArrayBuilder.ReverseContents(); // Case 3. Bind as handler. var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: false, additionalConstructorArguments: default, additionalConstructorRefKinds: default); // Now that the parts have been bound, reconstruct the binary operators. convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(stack, appendCalls, data, binaryOperator.Syntax, diagnostics); stack.Free(); return true; } private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(ArrayBuilder<BoundBinaryOperator> stack, ImmutableArray<ImmutableArray<BoundExpression>> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics) { Debug.Assert(appendCalls.Length == stack.Count + 1); var @string = GetSpecialType(SpecialType.System_String, diagnostics, rootSyntax); var bottomOperator = stack.Pop(); var result = createBinaryOperator(bottomOperator, createInterpolation(bottomOperator.Left, appendCalls[0]), rightIndex: 1); for (int i = 2; i < appendCalls.Length; i++) { result = createBinaryOperator(stack.Pop(), result, rightIndex: i); } return result.Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data)); BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, int rightIndex) => new BoundBinaryOperator( original.Syntax, BinaryOperatorKind.StringConcatenation, left, createInterpolation(original.Right, appendCalls[rightIndex]), original.ConstantValue, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, originalUserDefinedOperatorsOpt: default, @string, original.HasErrors); static BoundInterpolatedString createInterpolation(BoundExpression expression, ImmutableArray<BoundExpression> parts) { Debug.Assert(expression is BoundUnconvertedInterpolatedString); return new BoundInterpolatedString( expression.Syntax, interpolationData: null, parts, expression.ConstantValue, expression.Type, expression.HasErrors); } } private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType( BoundExpression unconvertedExpression, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) => unconvertedExpression switch { BoundUnconvertedInterpolatedString interpolatedString => BindUnconvertedInterpolatedStringToHandlerType( interpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds), BoundBinaryOperator binary => BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binary, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds), _ => throw ExceptionUtilities.UnexpectedValue(unconvertedExpression.Kind) }; private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType( BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) { var (appendCalls, interpolationData) = BindUnconvertedInterpolatedPartsToHandlerType( unconvertedInterpolatedString.Syntax, ImmutableArray.Create(unconvertedInterpolatedString.Parts), interpolatedStringHandlerType, diagnostics, isHandlerConversion, additionalConstructorArguments, additionalConstructorRefKinds); Debug.Assert(appendCalls.Length == 1); return new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, interpolationData, appendCalls[0], unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); } private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType( BoundBinaryOperator binaryOperator, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); BoundBinaryOperator? current = binaryOperator; while (current != null) { stack.Push(current); partsArrayBuilder.Add(((BoundUnconvertedInterpolatedString)current.Right).Parts); if (current.Left is BoundBinaryOperator next) { current = next; } else { partsArrayBuilder.Add(((BoundUnconvertedInterpolatedString)current.Left).Parts); current = null; } } // Parts are added in right to left order, but lexical is left to right. partsArrayBuilder.ReverseContents(); Debug.Assert(partsArrayBuilder.Count == stack.Count + 1); Debug.Assert(partsArrayBuilder.Count >= 2); var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds); var result = UpdateBinaryOperatorWithInterpolatedContents(stack, appendCalls, data, binaryOperator.Syntax, diagnostics); stack.Free(); return result; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType( SyntaxNode syntax, ImmutableArray<ImmutableArray<BoundExpression>> partsArray, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(additionalConstructorArguments.IsDefault ? additionalConstructorRefKinds.IsDefault : additionalConstructorArguments.Length == additionalConstructorRefKinds.Length); additionalConstructorArguments = additionalConstructorArguments.NullToEmpty(); additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty(); ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax); // We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if // there are errors we get better diagnostics than "could not convert to object." var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true }; var (appendCallsArray, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(partsArray, implicitBuilderReceiver, diagnostics); // Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types // (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there // is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components // are convertible to object if the current langversion is lower than the interpolation feature and we're converting this // interpolation into an actual string. bool needToCheckConversionToObject = false; if (isHandlerConversion) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics) { needToCheckConversionToObject = true; } Debug.Assert(appendCallsArray.Select(a => a.Length).SequenceEqual(partsArray.Select(a => a.Length))); Debug.Assert(appendCallsArray.All(appendCalls => appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation))); if (needToCheckConversionToObject) { TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, syntax); BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); foreach (var parts in partsArray) { foreach (var currentPart in parts) { if (currentPart is BoundStringInsert insert) { var value = insert.Value; bool reported = false; if (value.Type is not null) { value = BindToNaturalType(value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); reported = true; } } if (!reported) { _ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } } conversionDiagnostics.Clear(); } } } conversionDiagnostics.Free(); } var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, syntax); int constructorArgumentLength = 3 + additionalConstructorArguments.Length; var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength); refKindsBuilder.Add(RefKind.None); refKindsBuilder.Add(RefKind.None); refKindsBuilder.AddRange(additionalConstructorRefKinds); // Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean, // because we want to track that we're using the type no matter what. var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, syntax); var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType); var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder); refKindsBuilder.Add(RefKind.Out); populateArguments(syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); BoundExpression constructorCall; var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, outConstructorDiagnostics); if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which // could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate. argumentsBuilder.Clear(); // Try again without an out parameter. populateArguments(syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); refKindsBuilder.RemoveLast(); var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics); BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, nonOutConstructorDiagnostics); if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // We successfully bound the out version, so set all the final data based on that binding constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); } else { // We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find // a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed // for a different reason, that different reason is the one the user will want to know about. If both or neither failed // because of this error, we'll report everything. // https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload // resolution and attempting to determine which method considered was the best to report errors for. var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; switch ((nonOutConstructorHasArityError, outConstructorHasArityError)) { case (true, false): constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; diagnostics.AddRangeAndFree(outConstructorDiagnostics); nonOutConstructorDiagnostics.Free(); break; case (false, true): constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); break; default: // For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker, // but we'll report all diagnostics constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); diagnostics.AddRangeAndFree(outConstructorDiagnostics); break; } } } else { diagnostics.AddRangeAndFree(outConstructorDiagnostics); constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; } argumentsBuilder.Free(); refKindsBuilder.Free(); Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression); if (constructorCall is BoundDynamicObjectCreationExpression) { // An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name); } var interpolationData = new InterpolatedStringHandlerData( interpolatedStringHandlerType, constructorCall, usesBoolReturn, LocalScopeDepth, additionalConstructorArguments.NullToEmpty(), positionInfo, implicitBuilderReceiver); return (appendCallsArray, interpolationData); static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder) { // literalLength argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true }); // formattedCount argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true }); // Any other arguments from the call site argumentsBuilder.AddRange(additionalConstructorArguments); } } private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundExpression>? partsBuilder = null; var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) { var part = unconvertedInterpolatedString.Parts[i]; if (part is BoundStringInsert insert) { BoundExpression newValue; if (insert.Value.Type is null) { newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } else { newValue = BindToNaturalType(insert.Value, diagnostics); _ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } if (insert.Value != newValue) { if (partsBuilder is null) { partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length); partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i); } partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false)); } else { partsBuilder?.Add(part); } } else { Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } }); partsBuilder?.Add(part); } } return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls( ImmutableArray<ImmutableArray<BoundExpression>> partsArray, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) { if (partsArray.IsEmpty && partsArray.All(p => p.IsEmpty)) { return (ImmutableArray<ImmutableArray<BoundExpression>>.Empty, false, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.Empty, 0, 0); } bool? builderPatternExpectsBool = null; var firstPartsLength = partsArray[0].Length; var builderAppendCallsArray = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(partsArray.Length); var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(firstPartsLength); var positionInfoArray = ArrayBuilder<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.GetInstance(partsArray.Length); var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(firstPartsLength); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3); var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3); int baseStringLength = 0; int numFormatHoles = 0; foreach (var parts in partsArray) { foreach (var part in parts) { Debug.Assert(part is BoundLiteral or BoundStringInsert); string methodName; bool isLiteral; bool hasAlignment; bool hasFormat; if (part is BoundStringInsert insert) { methodName = "AppendFormatted"; argumentsBuilder.Add(insert.Value); parameterNamesAndLocationsBuilder.Add(null); isLiteral = false; hasAlignment = false; hasFormat = false; if (insert.Alignment is not null) { hasAlignment = true; argumentsBuilder.Add(insert.Alignment); parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location)); } if (insert.Format is not null) { hasFormat = true; argumentsBuilder.Add(insert.Format); parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location)); } numFormatHoles++; } else { var boundLiteral = (BoundLiteral)part; Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString); var literalText = ConstantValueUtils.UnescapeInterpolatedStringLiteral(boundLiteral.ConstantValue.StringValue); methodName = "AppendLiteral"; argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type)); isLiteral = true; hasAlignment = false; hasFormat = false; baseStringLength += literalText.Length; } var arguments = argumentsBuilder.ToImmutableAndClear(); ImmutableArray<(string, Location)?> parameterNamesAndLocations; if (parameterNamesAndLocationsBuilder.Count > 1) { parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear(); } else { Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null); parameterNamesAndLocations = default; parameterNamesAndLocationsBuilder.Clear(); } var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false); builderAppendCalls.Add(call); positionInfo.Add((isLiteral, hasAlignment, hasFormat)); Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true }); // We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that // void is returned. if (call is BoundCall { Method: { ReturnType: var returnType } method }) { bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean; if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void) { // Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method); } else if (builderPatternExpectsBool == null) { builderPatternExpectsBool = methodReturnsBool; } else if (builderPatternExpectsBool != methodReturnsBool) { // Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'. var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void); diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected); } } } builderAppendCallsArray.Add(builderAppendCalls.ToImmutableAndClear()); positionInfoArray.Add(positionInfo.ToImmutableAndClear()); } argumentsBuilder.Free(); parameterNamesAndLocationsBuilder.Free(); builderAppendCalls.Free(); positionInfo.Free(); return (builderAppendCallsArray.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfoArray.ToImmutableAndFree(), baseStringLength, numFormatHoles); } private BoundExpression BindInterpolatedStringHandlerInMemberCall( BoundExpression unconvertedString, ArrayBuilder<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, TypeSymbol? receiverType, RefKind? receiverRefKind, uint receiverEscapeScope, BindingDiagnosticBag diagnostics) { Debug.Assert(unconvertedString is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }); var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler); var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); Debug.Assert(interpolatedStringParameter is { Type: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } } #pragma warning disable format or { IsParams: true, Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } }, InterpolatedStringHandlerArgumentIndexes.IsEmpty: true }); #pragma warning restore format Debug.Assert(!interpolatedStringParameter.IsParams || memberAnalysisResult.Kind == MemberResolutionKind.ApplicableInExpandedForm); if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError) { // The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type); return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: false, interpolatedStringParameter.Type, diagnostics, hasErrors: true); } var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes; if (handlerParameterIndexes.IsEmpty) { // No arguments, fall back to the standard conversion steps. return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, interpolatedStringParameter.IsParams ? ((ArrayTypeSymbol)interpolatedStringParameter.Type).ElementType : interpolatedStringParameter.Type, diagnostics); } Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength, parameters.Length)); // We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter ImmutableArray<int> handlerArgumentIndexes; if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) { // No parameters are missing and no remapped indexes, we can just use the original indexes handlerArgumentIndexes = handlerParameterIndexes; } else { // Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter. var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++) { int handlerParameter = handlerParameterIndexes[handlerParameterIndex]; Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter) { handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter; continue; } for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++) { // The index in the original parameter list we're looking to match up. int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex); // Is the original parameter index of the current argument the parameter index that was specified in the attribute? if (argumentParameterIndex == handlerParameter) { // We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice. handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex; } } } handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree(); } var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length); var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length); bool hasErrors = false; // Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct // a set of placeholders for overload resolution. for (int i = 0; i < handlerArgumentIndexes.Length; i++) { int argumentIndex = handlerArgumentIndexes[i]; Debug.Assert(argumentIndex != interpolatedStringArgNum); RefKind refKind; TypeSymbol placeholderType; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiverRefKind != null && receiverType is not null); refKind = receiverRefKind.GetValueOrDefault(); placeholderType = receiverType; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: { // Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed. // If it is optional, then they could otherwise not specify the parameter and that's an error var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter))) { // Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; default: { var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (argumentIndex > interpolatedStringArgNum) { // Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[argumentIndex].Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; } SyntaxNode placeholderSyntax; uint valSafeToEscapeScope; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = receiverEscapeScope; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = Binder.ExternalScope; break; case >= 0: placeholderSyntax = arguments[argumentIndex].Syntax; valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth); break; default: throw ExceptionUtilities.UnexpectedValue(argumentIndex); } argumentPlaceholdersBuilder.Add( new BoundInterpolatedStringArgumentPlaceholder( placeholderSyntax, argumentIndex, valSafeToEscapeScope, placeholderType, hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter)); // We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors // about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will // be a place where refkinds are allowed to differ argumentRefKindsBuilder.Add(refKind); } var interpolatedString = BindUnconvertedInterpolatedExpressionToHandlerType( unconvertedString, (NamedTypeSymbol)interpolatedStringParameter.Type, diagnostics, additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(), additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree()); return new BoundConversion( interpolatedString.Syntax, interpolatedString, interpolatedStringConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, interpolatedStringParameter.Type, hasErrors || interpolatedString.HasErrors); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; 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 { private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(); var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node); ConstantValue? resultConstant = null; bool isResultConstant = true; if (node.Contents.Count == 0) { resultConstant = ConstantValue.Create(string.Empty); } else { var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); foreach (var content in node.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue); // We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering, // when we perform overload resolution, to report a problem. So we do that check by calling // GenerateConversionForAssignment with objectType. However we want to preserve the original expression's // natural type so that overload resolution may select a specialized implementation of string.Format, // so we discard the result of that call and only preserve its diagnostics. BoundExpression? alignment = null; BoundLiteral? format = null; if (interpolation.AlignmentClause != null) { alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics); var alignmentConstant = alignment.ConstantValue; if (alignmentConstant != null && !alignmentConstant.IsBad) { const int magnitudeLimit = 32767; // check that the magnitude of the alignment is "in range". int alignmentValue = alignmentConstant.Int32Value; // We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value. alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue; if (alignmentValue < -magnitudeLimit) { diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit); } } else if (!alignment.HasErrors) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location); } } if (interpolation.FormatClause != null) { var text = interpolation.FormatClause.FormatStringToken.ValueText; char lastChar; bool hasErrors = false; if (text.Length == 0) { diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar)) { diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors); } builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false)); if (!isResultConstant || value.ConstantValue == null || !(interpolation is { FormatClause: null, AlignmentClause: null }) || !(value.ConstantValue is { IsString: true, IsBad: false })) { isResultConstant = false; continue; } resultConstant = (resultConstant is null) ? value.ConstantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue); continue; } case SyntaxKind.InterpolatedStringText: { var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText; builder.Add(new BoundLiteral(content, ConstantValue.Create(text, SpecialType.System_String), stringType)); if (isResultConstant) { var constantVal = ConstantValue.Create(ConstantValueUtils.UnescapeInterpolatedStringLiteral(text), SpecialType.System_String); resultConstant = (resultConstant is null) ? constantVal : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantVal); } continue; } default: throw ExceptionUtilities.UnexpectedValue(content.Kind()); } } if (!isResultConstant) { resultConstant = null; } } Debug.Assert(isResultConstant == (resultConstant != null)); return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType); } private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { // We have 4 possible lowering strategies, dependent on the contents of the string, in this order: // 1. The string is a constant value. We can just use the final value. // 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a // params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and // make no intermediate allocations. // 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression. // The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any // awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation // hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for // the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected. // We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we // cannot put a try/finally inside a filter block. // 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single // call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this // call will need to allocate a param array. // 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await // expression. This is turned into a call to string.Format. // // We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being // able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering. if (unconvertedInterpolatedString.ConstantValue is not null) { // Case 1 Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String })); return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } // Case 2. Attempt to see if all parts are strings. if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts)) { return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } if (tryBindAsHandlerType(out var result)) { // Case 3 return result; } // The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible // object. return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) => new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result) { result = null; if (InExpressionTree || !InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType is MissingMetadataTypeSymbol) { return false; } result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false); return true; } } private static bool InterpolatedStringPartsAreValidInDefaultHandler(BoundUnconvertedInterpolatedString unconvertedInterpolatedString) => !unconvertedInterpolatedString.Parts.ContainsAwaitExpression() && unconvertedInterpolatedString.Parts.All(p => p is not BoundStringInsert { Value.Type.TypeKind: TypeKind.Dynamic }); private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray<BoundExpression> parts) => parts.All(p => p is BoundLiteral or BoundStringInsert { Value.Type.SpecialType: SpecialType.System_String, Alignment: null, Format: null }); private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator) { // Much like BindUnconvertedInterpolatedStringToString above, we only want to use DefaultInterpolatedStringHandler if it's worth it. We therefore // check for cases 1 and 2: if they are present, we let normal string binary operator binding machinery handle it. Otherwise, we take care of it ourselves. Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); convertedBinaryOperator = null; if (InExpressionTree) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType.IsErrorType()) { // Can't ever bind to the handler no matter what, so just let the default handling take care of it. Cases 4 and 5 are covered by this. return false; } // The constant value is folded as part of creating the unconverted operator. If there is a constant value, then the top-level binary operator // will have one. if (binaryOperator.ConstantValue is not null) { // This is case 1. Let the standard machinery handle it return false; } var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); if (!binaryOperator.VisitBinaryOperatorInterpolatedString( partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { if (!InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; })) { partsArrayBuilder.Free(); return false; } Debug.Assert(partsArrayBuilder.Count >= 2); if (partsArrayBuilder.Count <= 4 && partsArrayBuilder.All(static parts => AllInterpolatedStringPartsAreStrings(parts))) { // This is case 2. Let the standard machinery handle it partsArrayBuilder.Free(); return false; } // Case 3. Bind as handler. var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: false, additionalConstructorArguments: default, additionalConstructorRefKinds: default); // Now that the parts have been bound, reconstruct the binary operators. convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return true; } private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(BoundBinaryOperator originalOperator, ImmutableArray<ImmutableArray<BoundExpression>> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics) { var @string = GetSpecialType(SpecialType.System_String, diagnostics, rootSyntax); Func<BoundUnconvertedInterpolatedString, int, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> interpolationFactory = createInterpolation; Func<BoundBinaryOperator, BoundExpression, BoundExpression, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> binaryOperatorFactory = createBinaryOperator; var rewritten = (BoundBinaryOperator)originalOperator.RewriteInterpolatedStringAddition((appendCalls, @string), interpolationFactory, binaryOperatorFactory); return rewritten.Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data)); static BoundInterpolatedString createInterpolation(BoundUnconvertedInterpolatedString expression, int i, (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, TypeSymbol _) arg) { Debug.Assert(arg.AppendCalls.Length > i); return new BoundInterpolatedString( expression.Syntax, interpolationData: null, arg.AppendCalls[i], expression.ConstantValue, expression.Type, expression.HasErrors); } static BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, BoundExpression right, (ImmutableArray<ImmutableArray<BoundExpression>> _, TypeSymbol @string) arg) => new BoundBinaryOperator( original.Syntax, BinaryOperatorKind.StringConcatenation, left, right, original.ConstantValue, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, originalUserDefinedOperatorsOpt: default, arg.@string, original.HasErrors); } private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType( BoundExpression unconvertedExpression, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) => unconvertedExpression switch { BoundUnconvertedInterpolatedString interpolatedString => BindUnconvertedInterpolatedStringToHandlerType( interpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds), BoundBinaryOperator binary => BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binary, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds), _ => throw ExceptionUtilities.UnexpectedValue(unconvertedExpression.Kind) }; private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType( BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) { var (appendCalls, interpolationData) = BindUnconvertedInterpolatedPartsToHandlerType( unconvertedInterpolatedString.Syntax, ImmutableArray.Create(unconvertedInterpolatedString.Parts), interpolatedStringHandlerType, diagnostics, isHandlerConversion, additionalConstructorArguments, additionalConstructorRefKinds); Debug.Assert(appendCalls.Length == 1); return new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, interpolationData, appendCalls[0], unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); } private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType( BoundBinaryOperator binaryOperator, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); binaryOperator.VisitBinaryOperatorInterpolatedString(partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; }); var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds); var result = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return result; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType( SyntaxNode syntax, ImmutableArray<ImmutableArray<BoundExpression>> partsArray, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(additionalConstructorArguments.IsDefault ? additionalConstructorRefKinds.IsDefault : additionalConstructorArguments.Length == additionalConstructorRefKinds.Length); additionalConstructorArguments = additionalConstructorArguments.NullToEmpty(); additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty(); ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax); // We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if // there are errors we get better diagnostics than "could not convert to object." var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true }; var (appendCallsArray, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(partsArray, implicitBuilderReceiver, diagnostics); // Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types // (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there // is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components // are convertible to object if the current langversion is lower than the interpolation feature and we're converting this // interpolation into an actual string. bool needToCheckConversionToObject = false; if (isHandlerConversion) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics) { needToCheckConversionToObject = true; } Debug.Assert(appendCallsArray.Select(a => a.Length).SequenceEqual(partsArray.Select(a => a.Length))); Debug.Assert(appendCallsArray.All(appendCalls => appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation))); if (needToCheckConversionToObject) { TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, syntax); BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); foreach (var parts in partsArray) { foreach (var currentPart in parts) { if (currentPart is BoundStringInsert insert) { var value = insert.Value; bool reported = false; if (value.Type is not null) { value = BindToNaturalType(value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); reported = true; } } if (!reported) { _ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } } conversionDiagnostics.Clear(); } } } conversionDiagnostics.Free(); } var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, syntax); int constructorArgumentLength = 3 + additionalConstructorArguments.Length; var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength); refKindsBuilder.Add(RefKind.None); refKindsBuilder.Add(RefKind.None); refKindsBuilder.AddRange(additionalConstructorRefKinds); // Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean, // because we want to track that we're using the type no matter what. var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, syntax); var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType); var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder); refKindsBuilder.Add(RefKind.Out); populateArguments(syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); BoundExpression constructorCall; var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, outConstructorDiagnostics); if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which // could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate. argumentsBuilder.Clear(); // Try again without an out parameter. populateArguments(syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); refKindsBuilder.RemoveLast(); var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics); BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, nonOutConstructorDiagnostics); if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // We successfully bound the out version, so set all the final data based on that binding constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); } else { // We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find // a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed // for a different reason, that different reason is the one the user will want to know about. If both or neither failed // because of this error, we'll report everything. // https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload // resolution and attempting to determine which method considered was the best to report errors for. var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; switch ((nonOutConstructorHasArityError, outConstructorHasArityError)) { case (true, false): constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; diagnostics.AddRangeAndFree(outConstructorDiagnostics); nonOutConstructorDiagnostics.Free(); break; case (false, true): constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); break; default: // For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker, // but we'll report all diagnostics constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); diagnostics.AddRangeAndFree(outConstructorDiagnostics); break; } } } else { diagnostics.AddRangeAndFree(outConstructorDiagnostics); constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; } argumentsBuilder.Free(); refKindsBuilder.Free(); Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression); if (constructorCall is BoundDynamicObjectCreationExpression) { // An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name); } var interpolationData = new InterpolatedStringHandlerData( interpolatedStringHandlerType, constructorCall, usesBoolReturn, LocalScopeDepth, additionalConstructorArguments.NullToEmpty(), positionInfo, implicitBuilderReceiver); return (appendCallsArray, interpolationData); static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder) { // literalLength argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true }); // formattedCount argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true }); // Any other arguments from the call site argumentsBuilder.AddRange(additionalConstructorArguments); } } private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundExpression>? partsBuilder = null; var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) { var part = unconvertedInterpolatedString.Parts[i]; if (part is BoundStringInsert insert) { BoundExpression newValue; if (insert.Value.Type is null) { newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } else { newValue = BindToNaturalType(insert.Value, diagnostics); _ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } if (insert.Value != newValue) { if (partsBuilder is null) { partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length); partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i); } partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false)); } else { partsBuilder?.Add(part); } } else { Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } }); partsBuilder?.Add(part); } } return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls( ImmutableArray<ImmutableArray<BoundExpression>> partsArray, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) { if (partsArray.IsEmpty && partsArray.All(p => p.IsEmpty)) { return (ImmutableArray<ImmutableArray<BoundExpression>>.Empty, false, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.Empty, 0, 0); } bool? builderPatternExpectsBool = null; var firstPartsLength = partsArray[0].Length; var builderAppendCallsArray = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(partsArray.Length); var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(firstPartsLength); var positionInfoArray = ArrayBuilder<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.GetInstance(partsArray.Length); var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(firstPartsLength); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3); var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3); int baseStringLength = 0; int numFormatHoles = 0; foreach (var parts in partsArray) { foreach (var part in parts) { Debug.Assert(part is BoundLiteral or BoundStringInsert); string methodName; bool isLiteral; bool hasAlignment; bool hasFormat; if (part is BoundStringInsert insert) { methodName = "AppendFormatted"; argumentsBuilder.Add(insert.Value); parameterNamesAndLocationsBuilder.Add(null); isLiteral = false; hasAlignment = false; hasFormat = false; if (insert.Alignment is not null) { hasAlignment = true; argumentsBuilder.Add(insert.Alignment); parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location)); } if (insert.Format is not null) { hasFormat = true; argumentsBuilder.Add(insert.Format); parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location)); } numFormatHoles++; } else { var boundLiteral = (BoundLiteral)part; Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString); var literalText = ConstantValueUtils.UnescapeInterpolatedStringLiteral(boundLiteral.ConstantValue.StringValue); methodName = "AppendLiteral"; argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type)); isLiteral = true; hasAlignment = false; hasFormat = false; baseStringLength += literalText.Length; } var arguments = argumentsBuilder.ToImmutableAndClear(); ImmutableArray<(string, Location)?> parameterNamesAndLocations; if (parameterNamesAndLocationsBuilder.Count > 1) { parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear(); } else { Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null); parameterNamesAndLocations = default; parameterNamesAndLocationsBuilder.Clear(); } var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false); builderAppendCalls.Add(call); positionInfo.Add((isLiteral, hasAlignment, hasFormat)); Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true }); // We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that // void is returned. if (call is BoundCall { Method: { ReturnType: var returnType } method }) { bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean; if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void) { // Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method); } else if (builderPatternExpectsBool == null) { builderPatternExpectsBool = methodReturnsBool; } else if (builderPatternExpectsBool != methodReturnsBool) { // Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'. var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void); diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected); } } } builderAppendCallsArray.Add(builderAppendCalls.ToImmutableAndClear()); positionInfoArray.Add(positionInfo.ToImmutableAndClear()); } argumentsBuilder.Free(); parameterNamesAndLocationsBuilder.Free(); builderAppendCalls.Free(); positionInfo.Free(); return (builderAppendCallsArray.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfoArray.ToImmutableAndFree(), baseStringLength, numFormatHoles); } private BoundExpression BindInterpolatedStringHandlerInMemberCall( BoundExpression unconvertedString, ArrayBuilder<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, TypeSymbol? receiverType, RefKind? receiverRefKind, uint receiverEscapeScope, BindingDiagnosticBag diagnostics) { Debug.Assert(unconvertedString is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }); var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler); var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); Debug.Assert(interpolatedStringParameter is { Type: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } } #pragma warning disable format or { IsParams: true, Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } }, InterpolatedStringHandlerArgumentIndexes.IsEmpty: true }); #pragma warning restore format Debug.Assert(!interpolatedStringParameter.IsParams || memberAnalysisResult.Kind == MemberResolutionKind.ApplicableInExpandedForm); if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError) { // The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type); return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: false, interpolatedStringParameter.Type, diagnostics, hasErrors: true); } var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes; if (handlerParameterIndexes.IsEmpty) { // No arguments, fall back to the standard conversion steps. return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, interpolatedStringParameter.IsParams ? ((ArrayTypeSymbol)interpolatedStringParameter.Type).ElementType : interpolatedStringParameter.Type, diagnostics); } Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength, parameters.Length)); // We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter ImmutableArray<int> handlerArgumentIndexes; if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) { // No parameters are missing and no remapped indexes, we can just use the original indexes handlerArgumentIndexes = handlerParameterIndexes; } else { // Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter. var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++) { int handlerParameter = handlerParameterIndexes[handlerParameterIndex]; Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter) { handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter; continue; } for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++) { // The index in the original parameter list we're looking to match up. int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex); // Is the original parameter index of the current argument the parameter index that was specified in the attribute? if (argumentParameterIndex == handlerParameter) { // We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice. handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex; } } } handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree(); } var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length); var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length); bool hasErrors = false; // Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct // a set of placeholders for overload resolution. for (int i = 0; i < handlerArgumentIndexes.Length; i++) { int argumentIndex = handlerArgumentIndexes[i]; Debug.Assert(argumentIndex != interpolatedStringArgNum); RefKind refKind; TypeSymbol placeholderType; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiverRefKind != null && receiverType is not null); refKind = receiverRefKind.GetValueOrDefault(); placeholderType = receiverType; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: { // Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed. // If it is optional, then they could otherwise not specify the parameter and that's an error var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter))) { // Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; default: { var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (argumentIndex > interpolatedStringArgNum) { // Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[argumentIndex].Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; } SyntaxNode placeholderSyntax; uint valSafeToEscapeScope; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = receiverEscapeScope; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = Binder.ExternalScope; break; case >= 0: placeholderSyntax = arguments[argumentIndex].Syntax; valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth); break; default: throw ExceptionUtilities.UnexpectedValue(argumentIndex); } argumentPlaceholdersBuilder.Add( new BoundInterpolatedStringArgumentPlaceholder( placeholderSyntax, argumentIndex, valSafeToEscapeScope, placeholderType, hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter)); // We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors // about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will // be a place where refkinds are allowed to differ argumentRefKindsBuilder.Add(refKind); } var interpolatedString = BindUnconvertedInterpolatedExpressionToHandlerType( unconvertedString, (NamedTypeSymbol)interpolatedStringParameter.Type, diagnostics, additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(), additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree()); return new BoundConversion( interpolatedString.Syntax, interpolatedString, interpolatedStringConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, interpolatedStringParameter.Type, hasErrors || interpolatedString.HasErrors); } } }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { node.Left.CheckDeconstructionCompatibleArgument(diagnostics); BoundExpression left = BindValue(node.Left, diagnostics, GetBinaryAssignmentKind(node.Kind())); ReportSuppressionIfNeeded(left, diagnostics); BoundExpression right = BindValue(node.Right, diagnostics, BindValueKind.RValue); BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind()); // If either operand is bad, don't try to do binary operator overload resolution; that will just // make cascading errors. if (left.Kind == BoundKind.EventAccess) { BinaryOperatorKind kindOperator = kind.Operator(); switch (kindOperator) { case BinaryOperatorKind.Addition: case BinaryOperatorKind.Subtraction: return BindEventAssignment(node, (BoundEventAccess)left, right, kindOperator, diagnostics); // fall-through for other operators, if RHS is dynamic we produce dynamic operation, otherwise we'll report an error ... } } if (left.HasAnyErrors || right.HasAnyErrors) { // NOTE: no overload resolution candidates. left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (left.HasDynamicType() || right.HasDynamicType()) { if (IsLegalDynamicOperand(right) && IsLegalDynamicOperand(left)) { left = BindToNaturalType(left, diagnostics); right = BindToNaturalType(right, diagnostics); var finalDynamicConversion = this.Compilation.Conversions.ClassifyConversionFromExpression(right, left.Type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); return new BoundCompoundAssignmentOperator( node, new BinaryOperatorSignature( kind.WithType(BinaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), left.Type, right.Type, Compilation.DynamicType), left, right, Conversion.NoConversion, finalDynamicConversion, LookupResultKind.Viable, left.Type, hasErrors: false); } else { Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, node.OperatorToken.Text, left.Display, right.Display); // error: operator can't be applied on dynamic and a type that is not convertible to dynamic: left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); } } if (left.Kind == BoundKind.EventAccess && !CheckEventValueKind((BoundEventAccess)left, BindValueKind.Assignable, diagnostics)) { // If we're in a place where the event can be assigned, then continue so that we give errors // about the types and operator not lining up. Otherwise, just report that the event can't // be used here. // NOTE: no overload resolution candidates. left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.NotAVariable, CreateErrorType(), hasErrors: true); } // A compound operator, say, x |= y, is bound as x = (X)( ((T)x) | ((T)y) ). We must determine // the binary operator kind, the type conversions from each side to the types expected by // the operator, and the type conversion from the return type of the operand to the left hand side. // // We can get away with binding the right-hand-side of the operand into its converted form early. // This is convenient because first, it is never rewritten into an access to a temporary before // the conversion, and second, because that is more convenient for the "d += lambda" case. // We want to have the converted (bound) lambda in the bound tree, not the unconverted unbound lambda. LookupResultKind resultKind; ImmutableArray<MethodSymbol> originalUserDefinedOperators; BinaryOperatorAnalysisResult best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); if (!best.HasValue) { ReportAssignmentOperatorError(node, diagnostics, left, right, resultKind); left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, Conversion.NoConversion, Conversion.NoConversion, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); } // The rules in the spec for determining additional errors are bit confusing. In particular // this line is misleading: // // "for predefined operators ... x op= y is permitted if both x op y and x = y are permitted" // // That's not accurate in many cases. For example, "x += 1" is permitted if x is string or // any enum type, but x = 1 is not legal for strings or enums. // // The correct rules are spelled out in the spec: // // Spec §7.17.2: // An operation of the form x op= y is processed by applying binary operator overload // resolution (§7.3.4) as if the operation was written x op y. // Let R be the return type of the selected operator, and T the type of x. Then, // // * If an implicit conversion from an expression of type R to the type T exists, // the operation is evaluated as x = (T)(x op y), except that x is evaluated only once. // [no cast is inserted, unless the conversion is implicit dynamic] // * Otherwise, if // (1) the selected operator is a predefined operator, // (2) if R is explicitly convertible to T, and // (3.1) if y is implicitly convertible to T or // (3.2) the operator is a shift operator... [then cast the result to T] // * Otherwise ... a binding-time error occurs. // So let's tease that out. There are two possible errors: the conversion from the // operator result type to the left hand type could be bad, and the conversion // from the right hand side to the left hand type could be bad. // // We report the first error under the following circumstances: // // * The final conversion is bad, or // * The final conversion is explicit and the selected operator is not predefined // // We report the second error under the following circumstances: // // * The final conversion is explicit, and // * The selected operator is predefined, and // * the selected operator is not a shift, and // * the right-to-left conversion is not implicit bool hasError = false; BinaryOperatorSignature bestSignature = best.Signature; CheckNativeIntegerFeatureAvailability(bestSignature.Kind, node, diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, bestSignature.Method, bestSignature.ConstrainedToTypeOpt, diagnostics); if (CheckOverflowAtRuntime) { bestSignature = new BinaryOperatorSignature( bestSignature.Kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), bestSignature.LeftType, bestSignature.RightType, bestSignature.ReturnType, bestSignature.Method, bestSignature.ConstrainedToTypeOpt); } BoundExpression rightConverted = CreateConversion(right, best.RightConversion, bestSignature.RightType, diagnostics); var leftType = left.Type; Conversion finalConversion = Conversions.ClassifyConversionFromExpressionType(bestSignature.ReturnType, leftType, ref useSiteInfo); bool isPredefinedOperator = !bestSignature.Kind.IsUserDefined(); if (!finalConversion.IsValid || finalConversion.IsExplicit && !isPredefinedOperator) { hasError = true; GenerateImplicitConversionError(diagnostics, this.Compilation, node, finalConversion, bestSignature.ReturnType, leftType); } else { ReportDiagnosticsIfObsolete(diagnostics, finalConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, finalConversion, diagnostics); } if (finalConversion.IsExplicit && isPredefinedOperator && !kind.IsShift()) { Conversion rightToLeftConversion = this.Conversions.ClassifyConversionFromExpression(right, leftType, ref useSiteInfo); if (!rightToLeftConversion.IsImplicit || !rightToLeftConversion.IsValid) { hasError = true; GenerateImplicitConversionError(diagnostics, node, rightToLeftConversion, right, leftType); } } diagnostics.Add(node, useSiteInfo); if (!hasError && leftType.IsVoidPointer()) { Error(diagnostics, ErrorCode.ERR_VoidError, node); hasError = true; } // Any events that weren't handled above (by BindEventAssignment) are bad - we just followed this // code path for the diagnostics. Make sure we don't report success. Debug.Assert(left.Kind != BoundKind.EventAccess || hasError); Conversion leftConversion = best.LeftConversion; ReportDiagnosticsIfObsolete(diagnostics, leftConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, leftConversion, diagnostics); return new BoundCompoundAssignmentOperator(node, bestSignature, left, rightConverted, leftConversion, finalConversion, resultKind, originalUserDefinedOperators, leftType, hasError); } /// <summary> /// For "receiver.event += expr", produce "receiver.add_event(expr)". /// For "receiver.event -= expr", produce "receiver.remove_event(expr)". /// </summary> /// <remarks> /// Performs some validation of the accessor that couldn't be done in CheckEventValueKind, because /// the specific accessor wasn't known. /// </remarks> private BoundExpression BindEventAssignment(AssignmentExpressionSyntax node, BoundEventAccess left, BoundExpression right, BinaryOperatorKind opKind, BindingDiagnosticBag diagnostics) { Debug.Assert(opKind == BinaryOperatorKind.Addition || opKind == BinaryOperatorKind.Subtraction); bool hasErrors = false; EventSymbol eventSymbol = left.EventSymbol; BoundExpression receiverOpt = left.ReceiverOpt; TypeSymbol delegateType = left.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion argumentConversion = this.Conversions.ClassifyConversionFromExpression(right, delegateType, ref useSiteInfo); if (!argumentConversion.IsImplicit || !argumentConversion.IsValid) // NOTE: dev10 appears to allow user-defined conversions here. { hasErrors = true; if (delegateType.IsDelegateType()) // Otherwise, suppress cascading. { GenerateImplicitConversionError(diagnostics, node, argumentConversion, right, delegateType); } } BoundExpression argument = CreateConversion(right, argumentConversion, delegateType, diagnostics); bool isAddition = opKind == BinaryOperatorKind.Addition; MethodSymbol method = isAddition ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; TypeSymbol type; if ((object)method == null) { type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); //we know the return type would have been void // There will be a diagnostic on the declaration if it is from source. if (!eventSymbol.OriginalDefinition.IsFromCompilation(this.Compilation)) { // CONSIDER: better error code? ERR_EventNeedsBothAccessors? Error(diagnostics, ErrorCode.ERR_MissingPredefinedMember, node, delegateType, SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAddition)); } } else { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, method, diagnostics); if (!this.IsAccessible(method, ref useSiteInfo, this.GetAccessThroughType(receiverOpt))) { // CONSIDER: depending on the accessibility (e.g. if it's private), dev10 might just report the whole event bogus. Error(diagnostics, ErrorCode.ERR_BadAccess, node, method); hasErrors = true; } else if (IsBadBaseAccess(node, receiverOpt, method, diagnostics, eventSymbol)) { hasErrors = true; } else { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, method, diagnostics); } if (eventSymbol.IsWindowsRuntimeEvent) { // Return type is actually void because this call will be later encapsulated in a call // to WindowsRuntimeMarshal.AddEventHandler or RemoveEventHandler, which has the return // type of void. type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); } else { type = method.ReturnType; } } diagnostics.Add(node, useSiteInfo); return new BoundEventAssignmentOperator( syntax: node, @event: eventSymbol, isAddition: isAddition, isDynamic: right.HasDynamicType(), receiverOpt: receiverOpt, argument: argument, type: type, hasErrors: hasErrors); } private static bool IsLegalDynamicOperand(BoundExpression operand) { Debug.Assert(operand != null); TypeSymbol type = operand.Type; // Literal null is a legal operand to a dynamic operation. The other typeless expressions -- // method groups, lambdas, anonymous methods -- are not. // If the operand is of a class, interface, delegate, array, struct, enum, nullable // or type param types, it's legal to use in a dynamic expression. In short, the type // must be one that is convertible to object. if ((object)type == null) { return operand.IsLiteralNull(); } // Pointer types and very special types are not convertible to object. return !type.IsPointerOrFunctionPointer() && !type.IsRestrictedType() && !type.IsVoidType(); } private BoundExpression BindDynamicBinaryOperator( BinaryExpressionSyntax node, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) { // This method binds binary * / % + - << >> < > <= >= == != & ! ^ && || operators where one or both // of the operands are dynamic. Debug.Assert((object)left.Type != null && left.Type.IsDynamic() || (object)right.Type != null && right.Type.IsDynamic()); bool hasError = false; bool leftValidOperand = IsLegalDynamicOperand(left); bool rightValidOperand = IsLegalDynamicOperand(right); if (!leftValidOperand || !rightValidOperand) { // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, node.OperatorToken.Text, left.Display, right.Display); hasError = true; } MethodSymbol userDefinedOperator = null; if (kind.IsLogical() && leftValidOperand) { // We need to make sure left is either implicitly convertible to Boolean or has user defined truth operator. // left && right is lowered to {op_False|op_Implicit}(left) ? left : And(left, right) // left || right is lowered to {op_True|!op_Implicit}(left) ? left : Or(left, right) CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (!IsValidDynamicCondition(left, isNegative: kind == BinaryOperatorKind.LogicalAnd, useSiteInfo: ref useSiteInfo, userDefinedOperator: out userDefinedOperator)) { // Dev11 reports ERR_MustHaveOpTF. The error was shared between this case and user-defined binary Boolean operators. // We report two distinct more specific error messages. Error(diagnostics, ErrorCode.ERR_InvalidDynamicCondition, node.Left, left.Type, kind == BinaryOperatorKind.LogicalAnd ? "false" : "true"); hasError = true; } else { Debug.Assert(left.Type is not TypeParameterSymbol); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, userDefinedOperator, constrainedToTypeOpt: null, diagnostics); } diagnostics.Add(node, useSiteInfo); } return new BoundBinaryOperator( syntax: node, operatorKind: (hasError ? kind : kind.WithType(BinaryOperatorKind.Dynamic)).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), left: BindToNaturalType(left, diagnostics), right: BindToNaturalType(right, diagnostics), constantValueOpt: ConstantValue.NotAvailable, methodOpt: userDefinedOperator, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, type: Compilation.DynamicType, hasErrors: hasError); } protected static bool IsSimpleBinaryOperator(SyntaxKind kind) { // We deliberately exclude &&, ||, ??, etc. switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: return true; } return false; } private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { // The simple binary operators are left-associative, and expressions of the form // a + b + c + d .... are relatively common in machine-generated code. The parser can handle // creating a deep-on-the-left syntax tree no problem, and then we promptly blow the stack during // semantic analysis. Here we build an explicit stack to handle the left-hand recursion. Debug.Assert(IsSimpleBinaryOperator(node.Kind())); var syntaxNodes = ArrayBuilder<BinaryExpressionSyntax>.GetInstance(); ExpressionSyntax current = node; while (IsSimpleBinaryOperator(current.Kind())) { var binOp = (BinaryExpressionSyntax)current; syntaxNodes.Push(binOp); current = binOp.Left; } BoundExpression result = BindExpression(current, diagnostics); if (node.IsKind(SyntaxKind.SubtractExpression) && current.IsKind(SyntaxKind.ParenthesizedExpression)) { if (result.Kind == BoundKind.TypeExpression && !((ParenthesizedExpressionSyntax)current).Expression.IsKind(SyntaxKind.ParenthesizedExpression)) { Error(diagnostics, ErrorCode.ERR_PossibleBadNegCast, node); } else if (result.Kind == BoundKind.BadExpression) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)current; if (parenthesizedExpression.Expression.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)parenthesizedExpression.Expression).Identifier.ValueText == "dynamic") { Error(diagnostics, ErrorCode.ERR_PossibleBadNegCast, node); } } } while (syntaxNodes.Count > 0) { BinaryExpressionSyntax syntaxNode = syntaxNodes.Pop(); BindValueKind bindValueKind = GetBinaryAssignmentKind(syntaxNode.Kind()); BoundExpression left = CheckValue(result, bindValueKind, diagnostics); BoundExpression right = BindValue(syntaxNode.Right, diagnostics, BindValueKind.RValue); BoundExpression boundOp = BindSimpleBinaryOperator(syntaxNode, diagnostics, left, right, leaveUnconvertedIfInterpolatedString: true); result = boundOp; } syntaxNodes.Free(); return result; } private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, bool leaveUnconvertedIfInterpolatedString) { BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind()); // If either operand is bad, don't try to do binary operator overload resolution; that would just // make cascading errors. if (left.HasAnyErrors || right.HasAnyErrors) { // NOTE: no user-defined conversion candidates left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundBinaryOperator(node, kind, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Empty, left, right, GetBinaryOperatorErrorType(kind, diagnostics, node), true); } TypeSymbol leftType = left.Type; TypeSymbol rightType = right.Type; if ((object)leftType != null && leftType.IsDynamic() || (object)rightType != null && rightType.IsDynamic()) { return BindDynamicBinaryOperator(node, kind, left, right, diagnostics); } // SPEC OMISSION: The C# 2.0 spec had a line in it that noted that the expressions "null == null" // SPEC OMISSION: and "null != null" were to be automatically treated as the appropriate constant; // SPEC OMISSION: overload resolution was to be skipped. That's because a strict reading // SPEC OMISSION: of the overload resolution spec shows that overload resolution would give an // SPEC OMISSION: ambiguity error for this case; the expression is ambiguous between the int?, // SPEC OMISSION: bool? and string versions of equality. This line was accidentally edited // SPEC OMISSION: out of the C# 3 specification; we should re-insert it. bool leftNull = left.IsLiteralNull(); bool rightNull = right.IsLiteralNull(); bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual; if (isEquality && leftNull && rightNull) { return new BoundLiteral(node, ConstantValue.Create(kind == BinaryOperatorKind.Equal), GetSpecialType(SpecialType.System_Boolean, diagnostics, node)); } if (IsTupleBinaryOperation(left, right) && (kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual)) { CheckFeatureAvailability(node, MessageID.IDS_FeatureTupleEquality, diagnostics); return BindTupleBinaryOperator(node, kind, left, right, diagnostics); } if (leaveUnconvertedIfInterpolatedString && kind == BinaryOperatorKind.Addition && left is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true } && right is BoundUnconvertedInterpolatedString) { Debug.Assert(right.Type.SpecialType == SpecialType.System_String); var stringConstant = FoldBinaryOperator(node, BinaryOperatorKind.StringConcatenation, left, right, right.Type, diagnostics); return new BoundBinaryOperator(node, BinaryOperatorKind.StringConcatenation, BoundBinaryOperator.UncommonData.UnconvertedInterpolatedStringAddition(stringConstant), LookupResultKind.Empty, left, right, right.Type); } // SPEC: For an operation of one of the forms x == null, null == x, x != null, null != x, // SPEC: where x is an expression of nullable type, if operator overload resolution // SPEC: fails to find an applicable operator, the result is instead computed from // SPEC: the HasValue property of x. // Note that the spec says "fails to find an applicable operator", not "fails to // find a unique best applicable operator." For example: // struct X { // public static bool operator ==(X? x, double? y) {...} // public static bool operator ==(X? x, decimal? y) {...} // // The comparison "x == null" should produce an ambiguity error rather // that being bound as !x.HasValue. // LookupResultKind resultKind; ImmutableArray<MethodSymbol> originalUserDefinedOperators; BinaryOperatorSignature signature; BinaryOperatorAnalysisResult best; bool foundOperator = BindSimpleBinaryOperatorParts(node, diagnostics, left, right, kind, out resultKind, out originalUserDefinedOperators, out signature, out best); BinaryOperatorKind resultOperatorKind = signature.Kind; bool hasErrors = false; if (!foundOperator) { ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind); resultOperatorKind &= ~BinaryOperatorKind.TypeMask; hasErrors = true; } switch (node.Kind()) { case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: // Function pointer comparisons are defined on `void*` with implicit conversions to `void*` on both sides. So if this is a // pointer comparison operation, and the underlying types of the left and right are both function pointers, then we need to // warn about them because of JIT recompilation. If either side is explicitly cast to void*, that side's type will be void*, // not delegate*, and we won't warn. if ((resultOperatorKind & BinaryOperatorKind.Pointer) == BinaryOperatorKind.Pointer && leftType?.TypeKind == TypeKind.FunctionPointer && rightType?.TypeKind == TypeKind.FunctionPointer) { // Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct. Error(diagnostics, ErrorCode.WRN_DoNotCompareFunctionPointers, node.OperatorToken); } break; default: if (leftType.IsVoidPointer() || rightType.IsVoidPointer()) { // CONSIDER: dev10 cascades this, but roslyn doesn't have to. Error(diagnostics, ErrorCode.ERR_VoidError, node); hasErrors = true; } break; } CheckNativeIntegerFeatureAvailability(resultOperatorKind, node, diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); TypeSymbol resultType = signature.ReturnType; BoundExpression resultLeft = left; BoundExpression resultRight = right; ConstantValue resultConstant = null; if (foundOperator && (resultOperatorKind.OperandTypes() != BinaryOperatorKind.NullableNull)) { Debug.Assert((object)signature.LeftType != null); Debug.Assert((object)signature.RightType != null); resultLeft = CreateConversion(left, best.LeftConversion, signature.LeftType, diagnostics); resultRight = CreateConversion(right, best.RightConversion, signature.RightType, diagnostics); resultConstant = FoldBinaryOperator(node, resultOperatorKind, resultLeft, resultRight, resultType, diagnostics); } else { // If we found an operator, we'll have given the `default` literal a type. // Otherwise, we'll have reported the problem in ReportBinaryOperatorError. resultLeft = BindToNaturalType(resultLeft, diagnostics, reportNoTargetType: false); resultRight = BindToNaturalType(resultRight, diagnostics, reportNoTargetType: false); } hasErrors = hasErrors || resultConstant != null && resultConstant.IsBad; return new BoundBinaryOperator( node, resultOperatorKind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), resultLeft, resultRight, resultConstant, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, resultType, hasErrors); } private bool BindSimpleBinaryOperatorParts(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, BinaryOperatorKind kind, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators, out BinaryOperatorSignature resultSignature, out BinaryOperatorAnalysisResult best) { bool foundOperator; best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); // However, as an implementation detail, we never "fail to find an applicable // operator" during overload resolution if we have x == null, x == default, etc. We always // find at least the reference conversion object == object; the overload resolution // code does not reject that. Therefore what we should do is only bind // "x == null" as a nullable-to-null comparison if overload resolution chooses // the reference conversion. if (!best.HasValue) { resultSignature = new BinaryOperatorSignature(kind, leftType: null, rightType: null, CreateErrorType()); foundOperator = false; } else { var signature = best.Signature; bool isObjectEquality = signature.Kind == BinaryOperatorKind.ObjectEqual || signature.Kind == BinaryOperatorKind.ObjectNotEqual; bool leftNull = left.IsLiteralNull(); bool rightNull = right.IsLiteralNull(); TypeSymbol leftType = left.Type; TypeSymbol rightType = right.Type; bool isNullableEquality = (object)signature.Method == null && (signature.Kind.Operator() == BinaryOperatorKind.Equal || signature.Kind.Operator() == BinaryOperatorKind.NotEqual) && (leftNull && (object)rightType != null && rightType.IsNullableType() || rightNull && (object)leftType != null && leftType.IsNullableType()); if (isNullableEquality) { resultSignature = new BinaryOperatorSignature(kind | BinaryOperatorKind.NullableNull, leftType: null, rightType: null, GetSpecialType(SpecialType.System_Boolean, diagnostics, node)); foundOperator = true; } else { resultSignature = signature; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool leftDefault = left.IsLiteralDefault(); bool rightDefault = right.IsLiteralDefault(); foundOperator = !isObjectEquality || BuiltInOperators.IsValidObjectEquality(Conversions, leftType, leftNull, leftDefault, rightType, rightNull, rightDefault, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); } } return foundOperator; } #nullable enable private BoundExpression RebindSimpleBinaryOperatorAsConverted(BoundBinaryOperator unconvertedBinaryOperator, BindingDiagnosticBag diagnostics) { if (TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(unconvertedBinaryOperator, diagnostics, out var convertedBinaryOperator)) { return convertedBinaryOperator; } var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); BoundBinaryOperator? current = unconvertedBinaryOperator; while (current != null) { Debug.Assert(current.IsUnconvertedInterpolatedStringAddition); stack.Push(current); current = current.Left as BoundBinaryOperator; } Debug.Assert(stack.Count > 0 && stack.Peek().Left is BoundUnconvertedInterpolatedString); BoundExpression? left = null; while (stack.TryPop(out current)) { Debug.Assert(current.Right is BoundUnconvertedInterpolatedString); left = BindSimpleBinaryOperator((BinaryExpressionSyntax)current.Syntax, diagnostics, left ?? current.Left, current.Right, leaveUnconvertedIfInterpolatedString: false); } Debug.Assert(left != null); Debug.Assert(stack.Count == 0); stack.Free(); return left; } #nullable disable private static void ReportUnaryOperatorError(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, string operatorName, BoundExpression operand, LookupResultKind resultKind) { if (operand.IsLiteralDefault()) { // We'll have reported an error for not being able to target-type `default` so we can avoid a cascading diagnostic return; } ErrorCode errorCode = resultKind == LookupResultKind.Ambiguous ? ErrorCode.ERR_AmbigUnaryOp : // Operator '{0}' is ambiguous on an operand of type '{1}' ErrorCode.ERR_BadUnaryOp; // Operator '{0}' cannot be applied to operand of type '{1}' Error(diagnostics, errorCode, node, operatorName, operand.Display); } private void ReportAssignmentOperatorError(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, LookupResultKind resultKind) { if (((SyntaxKind)node.OperatorToken.RawKind == SyntaxKind.PlusEqualsToken || (SyntaxKind)node.OperatorToken.RawKind == SyntaxKind.MinusEqualsToken) && (object)left.Type != null && left.Type.TypeKind == TypeKind.Delegate) { // Special diagnostic for delegate += and -= about wrong right-hand-side var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = this.Conversions.ClassifyConversionFromExpression(right, left.Type, ref discardedUseSiteInfo); Debug.Assert(!conversion.IsImplicit); GenerateImplicitConversionError(diagnostics, right.Syntax, conversion, right, left.Type); // discard use-site diagnostics } else { ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind); } } private static void ReportBinaryOperatorError(ExpressionSyntax node, BindingDiagnosticBag diagnostics, SyntaxToken operatorToken, BoundExpression left, BoundExpression right, LookupResultKind resultKind) { bool isEquality = operatorToken.Kind() == SyntaxKind.EqualsEqualsToken || operatorToken.Kind() == SyntaxKind.ExclamationEqualsToken; switch (left.Kind, right.Kind) { case (BoundKind.DefaultLiteral, _) when !isEquality: case (_, BoundKind.DefaultLiteral) when !isEquality: // other than == and !=, binary operators are disallowed on `default` literal Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, "default"); return; case (BoundKind.DefaultLiteral, BoundKind.DefaultLiteral): Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnDefault, node, operatorToken.Text, left.Display, right.Display); return; case (BoundKind.DefaultLiteral, _) when right.Type is TypeParameterSymbol: Debug.Assert(!right.Type.IsReferenceType); Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault, node, operatorToken.Text, right.Type); return; case (_, BoundKind.DefaultLiteral) when left.Type is TypeParameterSymbol: Debug.Assert(!left.Type.IsReferenceType); Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault, node, operatorToken.Text, left.Type); return; case (BoundKind.UnconvertedObjectCreationExpression, _): Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, left.Display); return; case (_, BoundKind.UnconvertedObjectCreationExpression): Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, right.Display); return; } ErrorCode errorCode = resultKind == LookupResultKind.Ambiguous ? ErrorCode.ERR_AmbigBinaryOps : // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' ErrorCode.ERR_BadBinaryOps; // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' Error(diagnostics, errorCode, node, operatorToken.Text, left.Display, right.Display); } private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.LogicalOrExpression || node.Kind() == SyntaxKind.LogicalAndExpression); // Do not blow the stack due to a deep recursion on the left. BinaryExpressionSyntax binary = node; ExpressionSyntax child; while (true) { child = binary.Left; var childAsBinary = child as BinaryExpressionSyntax; if (childAsBinary == null || (childAsBinary.Kind() != SyntaxKind.LogicalOrExpression && childAsBinary.Kind() != SyntaxKind.LogicalAndExpression)) { break; } binary = childAsBinary; } BoundExpression left = BindRValueWithoutTargetType(child, diagnostics); do { binary = (BinaryExpressionSyntax)child.Parent; BoundExpression right = BindRValueWithoutTargetType(binary.Right, diagnostics); left = BindConditionalLogicalOperator(binary, left, right, diagnostics); child = binary; } while ((object)child != node); return left; } private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax node, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) { BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind()); Debug.Assert(kind == BinaryOperatorKind.LogicalAnd || kind == BinaryOperatorKind.LogicalOr); // Let's take an easy out here. The vast majority of the time the operands will // both be bool. This is the only situation in which the expression can be a // constant expression, so do the folding now if we can. if ((object)left.Type != null && left.Type.SpecialType == SpecialType.System_Boolean && (object)right.Type != null && right.Type.SpecialType == SpecialType.System_Boolean) { var constantValue = FoldBinaryOperator(node, kind | BinaryOperatorKind.Bool, left, right, left.Type, diagnostics); // NOTE: no candidate user-defined operators. return new BoundBinaryOperator(node, kind | BinaryOperatorKind.Bool, constantValue, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, left, right, type: left.Type, hasErrors: constantValue != null && constantValue.IsBad); } // If either operand is bad, don't try to do binary operator overload resolution; that will just // make cascading errors. if (left.HasAnyErrors || right.HasAnyErrors) { // NOTE: no candidate user-defined operators. return new BoundBinaryOperator(node, kind, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Empty, left, right, type: GetBinaryOperatorErrorType(kind, diagnostics, node), hasErrors: true); } if (left.HasDynamicType() || right.HasDynamicType()) { left = BindToNaturalType(left, diagnostics); right = BindToNaturalType(right, diagnostics); return BindDynamicBinaryOperator(node, kind, left, right, diagnostics); } LookupResultKind lookupResult; ImmutableArray<MethodSymbol> originalUserDefinedOperators; var best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out lookupResult, out originalUserDefinedOperators); // SPEC: If overload resolution fails to find a single best operator, or if overload // SPEC: resolution selects one of the predefined integer logical operators, a binding- // SPEC: time error occurs. // // SPEC OMISSION: We should probably clarify that the enum logical operators count as // SPEC OMISSION: integer logical operators. Basically the rule here should actually be: // SPEC OMISSION: if overload resolution selects something other than a user-defined // SPEC OMISSION: operator or the built in not-lifted operator on bool, an error occurs. // if (!best.HasValue) { ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, lookupResult); } else { // There are two non-error possibilities. Either both operands are implicitly convertible to // bool, or we've got a valid user-defined operator. BinaryOperatorSignature signature = best.Signature; bool bothBool = signature.LeftType.SpecialType == SpecialType.System_Boolean && signature.RightType.SpecialType == SpecialType.System_Boolean; MethodSymbol trueOperator = null, falseOperator = null; if (!bothBool && !signature.Kind.IsUserDefined()) { ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, lookupResult); } else if (bothBool || IsValidUserDefinedConditionalLogicalOperator(node, signature, diagnostics, out trueOperator, out falseOperator)) { var resultLeft = CreateConversion(left, best.LeftConversion, signature.LeftType, diagnostics); var resultRight = CreateConversion(right, best.RightConversion, signature.RightType, diagnostics); var resultKind = kind | signature.Kind.OperandTypes(); if (signature.Kind.IsLifted()) { resultKind |= BinaryOperatorKind.Lifted; } if (resultKind.IsUserDefined()) { Debug.Assert(trueOperator != null && falseOperator != null); _ = CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics) && CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, kind == BinaryOperatorKind.LogicalAnd ? falseOperator : trueOperator, signature.ConstrainedToTypeOpt, diagnostics); return new BoundUserDefinedConditionalLogicalOperator( node, resultKind, resultLeft, resultRight, signature.Method, trueOperator, falseOperator, signature.ConstrainedToTypeOpt, lookupResult, originalUserDefinedOperators, signature.ReturnType); } else { Debug.Assert(bothBool); Debug.Assert(!(signature.Method?.ContainingType?.IsInterface ?? false)); return new BoundBinaryOperator( node, resultKind, resultLeft, resultRight, ConstantValue.NotAvailable, signature.Method, signature.ConstrainedToTypeOpt, lookupResult, originalUserDefinedOperators, signature.ReturnType); } } } // We've already reported the error. return new BoundBinaryOperator(node, kind, left, right, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, lookupResult, originalUserDefinedOperators, CreateErrorType(), true); } private bool IsValidDynamicCondition(BoundExpression left, bool isNegative, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out MethodSymbol userDefinedOperator) { userDefinedOperator = null; var type = left.Type; if ((object)type == null) { return false; } if (type.IsDynamic()) { return true; } var implicitConversion = Conversions.ClassifyImplicitConversionFromExpression(left, Compilation.GetSpecialType(SpecialType.System_Boolean), ref useSiteInfo); if (implicitConversion.Exists) { return true; } if (type.Kind != SymbolKind.NamedType) { return false; } var namedType = type as NamedTypeSymbol; return HasApplicableBooleanOperator(namedType, isNegative ? WellKnownMemberNames.FalseOperatorName : WellKnownMemberNames.TrueOperatorName, type, ref useSiteInfo, out userDefinedOperator); } private bool IsValidUserDefinedConditionalLogicalOperator( CSharpSyntaxNode syntax, BinaryOperatorSignature signature, BindingDiagnosticBag diagnostics, out MethodSymbol trueOperator, out MethodSymbol falseOperator) { Debug.Assert(signature.Kind.OperandTypes() == BinaryOperatorKind.UserDefined); // SPEC: When the operands of && or || are of types that declare an applicable // SPEC: user-defined operator & or |, both of the following must be true, where // SPEC: T is the type in which the selected operator is defined: // SPEC VIOLATION: // // The native compiler violates the specification, the native compiler allows: // // public static D? operator &(D? d1, D? d2) { ... } // public static bool operator true(D? d) { ... } // public static bool operator false(D? d) { ... } // // to be used as D? && D? or D? || D?. But if you do this: // // public static D operator &(D d1, D d2) { ... } // public static bool operator true(D? d) { ... } // public static bool operator false(D? d) { ... } // // And use the *lifted* form of the operator, this is disallowed. // // public static D? operator &(D? d1, D d2) { ... } // public static bool operator true(D? d) { ... } // public static bool operator false(D? d) { ... } // // Is not allowed because "the return type must be the same as the type of both operands" // which is not at all what the spec says. // // We ought not to break backwards compatibility with the native compiler. The spec // is plausibly in error; it is possible that this section of the specification was // never updated when nullable types and lifted operators were added to the language. // And it seems like the native compiler's behavior of allowing a nullable // version but not a lifted version is a bug that should be fixed. // // Therefore we will do the following in Roslyn: // // * The return and parameter types of the chosen operator, whether lifted or unlifted, // must be the same. // * The return and parameter types must be either the enclosing type, or its corresponding // nullable type. // * There must be an operator true/operator false that takes the left hand type of the operator. // Only classes and structs contain user-defined operators, so we know it is a named type symbol. NamedTypeSymbol t = (NamedTypeSymbol)signature.Method.ContainingType; // SPEC: The return type and the type of each parameter of the selected operator // SPEC: must be T. // As mentioned above, we relax this restriction. The types must all be the same. bool typesAreSame = TypeSymbol.Equals(signature.LeftType, signature.RightType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(signature.LeftType, signature.ReturnType, TypeCompareKind.ConsiderEverything2); MethodSymbol definition; bool typeMatchesContainer = TypeSymbol.Equals(signature.ReturnType.StrippedType(), t, TypeCompareKind.ConsiderEverything2) || (t.IsInterface && signature.Method.IsAbstract && SourceUserDefinedOperatorSymbol.IsSelfConstrainedTypeParameter((definition = signature.Method.OriginalDefinition).ReturnType.StrippedType(), definition.ContainingType)); if (!typesAreSame || !typeMatchesContainer) { // CS0217: In order to be applicable as a short circuit operator a user-defined logical // operator ('{0}') must have the same return type and parameter types Error(diagnostics, ErrorCode.ERR_BadBoolOp, syntax, signature.Method); trueOperator = null; falseOperator = null; return false; } // SPEC: T must contain declarations of operator true and operator false. // As mentioned above, we need more than just op true and op false existing; we need // to know that the first operand can be passed to it. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (!HasApplicableBooleanOperator(t, WellKnownMemberNames.TrueOperatorName, signature.LeftType, ref useSiteInfo, out trueOperator) || !HasApplicableBooleanOperator(t, WellKnownMemberNames.FalseOperatorName, signature.LeftType, ref useSiteInfo, out falseOperator)) { // I have changed the wording of this error message. The original wording was: // CS0218: The type ('T') must contain declarations of operator true and operator false // I have changed that to: // CS0218: In order to be applicable as a short circuit operator, the declaring type // '{1}' of user-defined operator '{0}' must declare operator true and operator false. Error(diagnostics, ErrorCode.ERR_MustHaveOpTF, syntax, signature.Method, t); diagnostics.Add(syntax, useSiteInfo); trueOperator = null; falseOperator = null; return false; } diagnostics.Add(syntax, useSiteInfo); // For the remainder of this method the comments WOLOG assume that we're analyzing an &&. The // exact same issues apply to ||. // Note that the mere *existence* of operator true and operator false is sufficient. They // are already constrained to take either T or T?. Since we know that the applicable // T.& takes (T, T), we know that both sides of the && are implicitly convertible // to T, and therefore the left side is implicitly convertible to T or T?. // SPEC: The expression x && y is evaluated as T.false(x) ? x : T.&(x,y) ... except that // SPEC: x is only evaluated once. // // DELIBERATE SPEC VIOLATION: The native compiler does not actually evaluate x&&y in this // manner. Suppose X is of type X. The code above is equivalent to: // // X temp = x, then evaluate: // T.false(temp) ? temp : T.&(temp, y) // // What the native compiler actually evaluates is: // // T temp = x, then evaluate // T.false(temp) ? temp : T.&(temp, y) // // That is a small difference but it has an observable effect. For example: // // class V { public static implicit operator T(V v) { ... } } // class X : V { public static implicit operator T?(X x) { ... } } // struct T { // public static operator false(T? t) { ... } // public static operator true(T? t) { ... } // public static T operator &(T t1, T t2) { ... } // } // // Under the spec'd interpretation, if we had x of type X and y of type T then x && y is // // X temp = x; // T.false(temp) ? temp : T.&(temp, y) // // which would then be analyzed as: // // T.false(X.op_Implicit_To_Nullable_T(temp)) ? // V.op_Implicit_To_T(temp) : // T.&(op_Implicit_To_T(temp), y) // // But the native compiler actually generates: // // T temp = V.Op_Implicit_To_T(x); // T.false(new T?(temp)) ? temp : T.&(temp, y) // // That is, the native compiler converts the temporary to the type of the declaring operator type // regardless of the fact that there is a better conversion for the T.false call. // // We choose to match the native compiler behavior here; we might consider fixing // the spec to match the compiler. // // With this decision we need not keep track of any extra information in the bound // binary operator node; we need to know the left hand side converted to T, the right // hand side converted to T, and the method symbol of the chosen T.&(T, T) method. // The rewriting pass has enough information to deduce which T.false is to be called, // and can convert the T to T? if necessary. return true; } private bool HasApplicableBooleanOperator(NamedTypeSymbol containingType, string name, TypeSymbol argumentType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out MethodSymbol @operator) { for (var type = containingType; (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { var operators = type.GetOperators(name); for (var i = 0; i < operators.Length; i++) { var op = operators[i]; if (op.ParameterCount == 1 && op.DeclaredAccessibility == Accessibility.Public) { var conversion = this.Conversions.ClassifyConversionFromType(argumentType, op.GetParameterType(0), ref useSiteInfo); if (conversion.IsImplicit) { @operator = op; return true; } } } } @operator = null; return false; } private TypeSymbol GetBinaryOperatorErrorType(BinaryOperatorKind kind, BindingDiagnosticBag diagnostics, CSharpSyntaxNode node) { switch (kind) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: return GetSpecialType(SpecialType.System_Boolean, diagnostics, node); default: return CreateErrorType(); } } private BinaryOperatorAnalysisResult BinaryOperatorOverloadResolution(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators) { if (!IsTypelessExpressionAllowedInBinaryOperator(kind, left, right)) { resultKind = LookupResultKind.OverloadResolutionFailure; originalUserDefinedOperators = default(ImmutableArray<MethodSymbol>); return default(BinaryOperatorAnalysisResult); } var result = BinaryOperatorOverloadResolutionResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.OverloadResolution.BinaryOperatorOverloadResolution(kind, left, right, result, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); var possiblyBest = result.Best; if (result.Results.Any()) { var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var analysisResult in result.Results) { MethodSymbol method = analysisResult.Signature.Method; if ((object)method != null) { builder.Add(method); } } originalUserDefinedOperators = builder.ToImmutableAndFree(); if (possiblyBest.HasValue) { resultKind = LookupResultKind.Viable; } else if (result.AnyValid()) { resultKind = LookupResultKind.Ambiguous; } else { resultKind = LookupResultKind.OverloadResolutionFailure; } } else { originalUserDefinedOperators = ImmutableArray<MethodSymbol>.Empty; resultKind = possiblyBest.HasValue ? LookupResultKind.Viable : LookupResultKind.Empty; } if (possiblyBest is { HasValue: true, Signature: { Method: { } bestMethod } }) { ReportObsoleteAndFeatureAvailabilityDiagnostics(bestMethod, node, diagnostics); ReportUseSite(bestMethod, diagnostics, node); } result.Free(); return possiblyBest; } private void ReportObsoleteAndFeatureAvailabilityDiagnostics(MethodSymbol operatorMethod, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { if ((object)operatorMethod != null) { ReportDiagnosticsIfObsolete(diagnostics, operatorMethod, node, hasBaseReceiver: false); if (operatorMethod.ContainingType.IsInterface && operatorMethod.ContainingModule != Compilation.SourceModule) { Binder.CheckFeatureAvailability(node, MessageID.IDS_DefaultInterfaceImplementation, diagnostics); } } } private bool IsTypelessExpressionAllowedInBinaryOperator(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { // The default literal is only allowed with equality operators and both operands cannot be typeless at the same time. // Note: we only need to restrict expressions that can be converted to *any* type, in which case the resolution could always succeed. if (left.IsImplicitObjectCreation() || right.IsImplicitObjectCreation()) { return false; } bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual; if (isEquality) { return !left.IsLiteralDefault() || !right.IsLiteralDefault(); } else { return !left.IsLiteralDefault() && !right.IsLiteralDefault(); } } private UnaryOperatorAnalysisResult UnaryOperatorOverloadResolution( UnaryOperatorKind kind, BoundExpression operand, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators) { var result = UnaryOperatorOverloadResolutionResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.OverloadResolution.UnaryOperatorOverloadResolution(kind, operand, result, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); var possiblyBest = result.Best; if (result.Results.Any()) { var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var analysisResult in result.Results) { MethodSymbol method = analysisResult.Signature.Method; if ((object)method != null) { builder.Add(method); } } originalUserDefinedOperators = builder.ToImmutableAndFree(); if (possiblyBest.HasValue) { resultKind = LookupResultKind.Viable; } else if (result.AnyValid()) { // Special case: If we have the unary minus operator applied to a ulong, technically that should be // an ambiguity. The ulong could be implicitly converted to float, double or decimal, and then // the unary minus operator could be applied to the result. But though float is better than double, // float is neither better nor worse than decimal. However it seems odd to give an ambiguity error // when trying to do something such as applying a unary minus operator to an unsigned long. // The same issue applies to unary minus applied to nuint. if (kind == UnaryOperatorKind.UnaryMinus && (object)operand.Type != null && (operand.Type.SpecialType == SpecialType.System_UInt64 || (operand.Type.SpecialType == SpecialType.System_UIntPtr && operand.Type.IsNativeIntegerType))) { resultKind = LookupResultKind.OverloadResolutionFailure; } else { resultKind = LookupResultKind.Ambiguous; } } else { resultKind = LookupResultKind.OverloadResolutionFailure; } } else { originalUserDefinedOperators = ImmutableArray<MethodSymbol>.Empty; resultKind = possiblyBest.HasValue ? LookupResultKind.Viable : LookupResultKind.Empty; } if (possiblyBest is { HasValue: true, Signature: { Method: { } bestMethod } }) { ReportObsoleteAndFeatureAvailabilityDiagnostics(bestMethod, node, diagnostics); ReportUseSite(bestMethod, diagnostics, node); } result.Free(); return possiblyBest; } private static object FoldDecimalBinaryOperators(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); // Roslyn uses Decimal.operator+, operator-, etc. for both constant expressions and // non-constant expressions. Dev11 uses Decimal.operator+ etc. for non-constant // expressions only. This leads to different results between the two compilers // for certain constant expressions involving +/-0. (See bug #529730.) For instance, // +0 + -0 == +0 in Roslyn and == -0 in Dev11. Similarly, -0 - -0 == -0 in Roslyn, +0 in Dev11. // This is a breaking change from the native compiler but seems acceptable since // constant and non-constant expressions behave consistently in Roslyn. // (In Dev11, (+0 + -0) != (x + y) when x = +0, y = -0.) switch (kind) { case BinaryOperatorKind.DecimalAddition: return valueLeft.DecimalValue + valueRight.DecimalValue; case BinaryOperatorKind.DecimalSubtraction: return valueLeft.DecimalValue - valueRight.DecimalValue; case BinaryOperatorKind.DecimalMultiplication: return valueLeft.DecimalValue * valueRight.DecimalValue; case BinaryOperatorKind.DecimalDivision: return valueLeft.DecimalValue / valueRight.DecimalValue; case BinaryOperatorKind.DecimalRemainder: return valueLeft.DecimalValue % valueRight.DecimalValue; } return null; } private static object FoldNativeIntegerOverflowingBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); checked { switch (kind) { case BinaryOperatorKind.NIntAddition: return valueLeft.Int32Value + valueRight.Int32Value; case BinaryOperatorKind.NUIntAddition: return valueLeft.UInt32Value + valueRight.UInt32Value; case BinaryOperatorKind.NIntSubtraction: return valueLeft.Int32Value - valueRight.Int32Value; case BinaryOperatorKind.NUIntSubtraction: return valueLeft.UInt32Value - valueRight.UInt32Value; case BinaryOperatorKind.NIntMultiplication: return valueLeft.Int32Value * valueRight.Int32Value; case BinaryOperatorKind.NUIntMultiplication: return valueLeft.UInt32Value * valueRight.UInt32Value; case BinaryOperatorKind.NIntDivision: return valueLeft.Int32Value / valueRight.Int32Value; case BinaryOperatorKind.NIntRemainder: return valueLeft.Int32Value % valueRight.Int32Value; case BinaryOperatorKind.NIntLeftShift: { var int32Value = valueLeft.Int32Value << valueRight.Int32Value; var int64Value = valueLeft.Int64Value << valueRight.Int32Value; return (int32Value == int64Value) ? int32Value : null; } case BinaryOperatorKind.NUIntLeftShift: { var uint32Value = valueLeft.UInt32Value << valueRight.Int32Value; var uint64Value = valueLeft.UInt64Value << valueRight.Int32Value; return (uint32Value == uint64Value) ? uint32Value : null; } } return null; } } private static object FoldUncheckedIntegralBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); unchecked { switch (kind) { case BinaryOperatorKind.IntAddition: return valueLeft.Int32Value + valueRight.Int32Value; case BinaryOperatorKind.LongAddition: return valueLeft.Int64Value + valueRight.Int64Value; case BinaryOperatorKind.UIntAddition: return valueLeft.UInt32Value + valueRight.UInt32Value; case BinaryOperatorKind.ULongAddition: return valueLeft.UInt64Value + valueRight.UInt64Value; case BinaryOperatorKind.IntSubtraction: return valueLeft.Int32Value - valueRight.Int32Value; case BinaryOperatorKind.LongSubtraction: return valueLeft.Int64Value - valueRight.Int64Value; case BinaryOperatorKind.UIntSubtraction: return valueLeft.UInt32Value - valueRight.UInt32Value; case BinaryOperatorKind.ULongSubtraction: return valueLeft.UInt64Value - valueRight.UInt64Value; case BinaryOperatorKind.IntMultiplication: return valueLeft.Int32Value * valueRight.Int32Value; case BinaryOperatorKind.LongMultiplication: return valueLeft.Int64Value * valueRight.Int64Value; case BinaryOperatorKind.UIntMultiplication: return valueLeft.UInt32Value * valueRight.UInt32Value; case BinaryOperatorKind.ULongMultiplication: return valueLeft.UInt64Value * valueRight.UInt64Value; // even in unchecked context division may overflow: case BinaryOperatorKind.IntDivision: if (valueLeft.Int32Value == int.MinValue && valueRight.Int32Value == -1) { return int.MinValue; } return valueLeft.Int32Value / valueRight.Int32Value; case BinaryOperatorKind.LongDivision: if (valueLeft.Int64Value == long.MinValue && valueRight.Int64Value == -1) { return long.MinValue; } return valueLeft.Int64Value / valueRight.Int64Value; } return null; } } private static object FoldCheckedIntegralBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); checked { switch (kind) { case BinaryOperatorKind.IntAddition: return valueLeft.Int32Value + valueRight.Int32Value; case BinaryOperatorKind.LongAddition: return valueLeft.Int64Value + valueRight.Int64Value; case BinaryOperatorKind.UIntAddition: return valueLeft.UInt32Value + valueRight.UInt32Value; case BinaryOperatorKind.ULongAddition: return valueLeft.UInt64Value + valueRight.UInt64Value; case BinaryOperatorKind.IntSubtraction: return valueLeft.Int32Value - valueRight.Int32Value; case BinaryOperatorKind.LongSubtraction: return valueLeft.Int64Value - valueRight.Int64Value; case BinaryOperatorKind.UIntSubtraction: return valueLeft.UInt32Value - valueRight.UInt32Value; case BinaryOperatorKind.ULongSubtraction: return valueLeft.UInt64Value - valueRight.UInt64Value; case BinaryOperatorKind.IntMultiplication: return valueLeft.Int32Value * valueRight.Int32Value; case BinaryOperatorKind.LongMultiplication: return valueLeft.Int64Value * valueRight.Int64Value; case BinaryOperatorKind.UIntMultiplication: return valueLeft.UInt32Value * valueRight.UInt32Value; case BinaryOperatorKind.ULongMultiplication: return valueLeft.UInt64Value * valueRight.UInt64Value; case BinaryOperatorKind.IntDivision: return valueLeft.Int32Value / valueRight.Int32Value; case BinaryOperatorKind.LongDivision: return valueLeft.Int64Value / valueRight.Int64Value; } return null; } } internal static TypeSymbol GetEnumType(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { switch (kind) { case BinaryOperatorKind.EnumAndUnderlyingAddition: case BinaryOperatorKind.EnumAndUnderlyingSubtraction: case BinaryOperatorKind.EnumAnd: case BinaryOperatorKind.EnumOr: case BinaryOperatorKind.EnumXor: case BinaryOperatorKind.EnumEqual: case BinaryOperatorKind.EnumGreaterThan: case BinaryOperatorKind.EnumGreaterThanOrEqual: case BinaryOperatorKind.EnumLessThan: case BinaryOperatorKind.EnumLessThanOrEqual: case BinaryOperatorKind.EnumNotEqual: case BinaryOperatorKind.EnumSubtraction: return left.Type; case BinaryOperatorKind.UnderlyingAndEnumAddition: case BinaryOperatorKind.UnderlyingAndEnumSubtraction: return right.Type; default: throw ExceptionUtilities.UnexpectedValue(kind); } } internal static SpecialType GetEnumPromotedType(SpecialType underlyingType) { switch (underlyingType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: return SpecialType.System_Int32; case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return underlyingType; default: throw ExceptionUtilities.UnexpectedValue(underlyingType); } } #nullable enable private ConstantValue? FoldEnumBinaryOperator( CSharpSyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) { Debug.Assert(left != null); Debug.Assert(right != null); Debug.Assert(kind.IsEnum()); Debug.Assert(!kind.IsLifted()); // A built-in binary operation on constant enum operands is evaluated into an operation on // constants of the underlying type U of the enum type E. Comparison operators are lowered as // simply computing U<U. All other operators are computed as (E)(U op U) or in the case of // E-E, (U)(U-U). TypeSymbol enumType = GetEnumType(kind, left, right); TypeSymbol underlyingType = enumType.GetEnumUnderlyingType()!; BoundExpression newLeftOperand = CreateConversion(left, underlyingType, diagnostics); BoundExpression newRightOperand = CreateConversion(right, underlyingType, diagnostics); // If the underlying type is byte, sbyte, short, ushort or nullables of those then we'll need // to convert it up to int or int? because there are no + - * & | ^ < > <= >= == != operators // on byte, sbyte, short or ushort. They all convert to int. SpecialType operandSpecialType = GetEnumPromotedType(underlyingType.SpecialType); TypeSymbol operandType = (operandSpecialType == underlyingType.SpecialType) ? underlyingType : GetSpecialType(operandSpecialType, diagnostics, syntax); newLeftOperand = CreateConversion(newLeftOperand, operandType, diagnostics); newRightOperand = CreateConversion(newRightOperand, operandType, diagnostics); BinaryOperatorKind newKind = kind.Operator().WithType(newLeftOperand.Type!.SpecialType); switch (newKind.Operator()) { case BinaryOperatorKind.Addition: case BinaryOperatorKind.Subtraction: case BinaryOperatorKind.And: case BinaryOperatorKind.Or: case BinaryOperatorKind.Xor: resultTypeSymbol = operandType; break; case BinaryOperatorKind.LessThan: case BinaryOperatorKind.LessThanOrEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: Debug.Assert(resultTypeSymbol.SpecialType == SpecialType.System_Boolean); break; default: throw ExceptionUtilities.UnexpectedValue(newKind.Operator()); } var constantValue = FoldBinaryOperator(syntax, newKind, newLeftOperand, newRightOperand, resultTypeSymbol, diagnostics); if (resultTypeSymbol.SpecialType != SpecialType.System_Boolean && constantValue != null && !constantValue.IsBad) { TypeSymbol resultType = kind == BinaryOperatorKind.EnumSubtraction ? underlyingType : enumType; // We might need to convert back to the underlying type. return FoldConstantNumericConversion(syntax, constantValue, resultType, diagnostics); } return constantValue; } // Returns null if the operator can't be evaluated at compile time. private ConstantValue? FoldBinaryOperator( CSharpSyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) { Debug.Assert(left != null); Debug.Assert(right != null); if (left.HasAnyErrors || right.HasAnyErrors) { return null; } // SPEC VIOLATION: see method definition for details ConstantValue? nullableEqualityResult = TryFoldingNullableEquality(kind, left, right); if (nullableEqualityResult != null) { return nullableEqualityResult; } var valueLeft = left.ConstantValue; var valueRight = right.ConstantValue; if (valueLeft == null || valueRight == null) { return null; } if (valueLeft.IsBad || valueRight.IsBad) { return ConstantValue.Bad; } if (kind.IsEnum() && !kind.IsLifted()) { return FoldEnumBinaryOperator(syntax, kind, left, right, resultTypeSymbol, diagnostics); } // Divisions by zero on integral types and decimal always fail even in an unchecked context. if (IsDivisionByZero(kind, valueRight)) { Error(diagnostics, ErrorCode.ERR_IntDivByZero, syntax); return ConstantValue.Bad; } object? newValue = null; SpecialType resultType = resultTypeSymbol.SpecialType; // Certain binary operations never fail; bool & bool, for example. If we are in one of those // cases, simply fold the operation and return. // // Although remainder and division always overflow at runtime with arguments int.MinValue/long.MinValue and -1 // (regardless of checked context) the constant folding behavior is different. // Remainder never overflows at compile time while division does. newValue = FoldNeverOverflowBinaryOperators(kind, valueLeft, valueRight); if (newValue != null) { return ConstantValue.Create(newValue, resultType); } ConstantValue? concatResult = FoldStringConcatenation(kind, valueLeft, valueRight); if (concatResult != null) { if (concatResult.IsBad) { Error(diagnostics, ErrorCode.ERR_ConstantStringTooLong, right.Syntax); } return concatResult; } // Certain binary operations always fail if they overflow even when in an unchecked context; // decimal + decimal, for example. If we are in one of those cases, make the attempt. If it // succeeds, return the result. If not, give a compile-time error regardless of context. try { newValue = FoldDecimalBinaryOperators(kind, valueLeft, valueRight); } catch (OverflowException) { Error(diagnostics, ErrorCode.ERR_DecConstError, syntax); return ConstantValue.Bad; } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } try { newValue = FoldNativeIntegerOverflowingBinaryOperator(kind, valueLeft, valueRight); } catch (OverflowException) { if (CheckOverflowAtCompileTime) { Error(diagnostics, ErrorCode.WRN_CompileTimeCheckedOverflow, syntax, resultTypeSymbol); } return null; } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } if (CheckOverflowAtCompileTime) { try { newValue = FoldCheckedIntegralBinaryOperator(kind, valueLeft, valueRight); } catch (OverflowException) { Error(diagnostics, ErrorCode.ERR_CheckedOverflow, syntax); return ConstantValue.Bad; } } else { newValue = FoldUncheckedIntegralBinaryOperator(kind, valueLeft, valueRight); } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } return null; } /// <summary> /// If one of the (unconverted) operands has constant value null and the other has /// a null constant value other than null, then they are definitely not equal /// and we can give a constant value for either == or !=. This is a spec violation /// that we retain from Dev10. /// </summary> /// <param name="kind">The operator kind. Nothing will happen if it is not a lifted equality operator.</param> /// <param name="left">The left-hand operand of the operation (possibly wrapped in a conversion).</param> /// <param name="right">The right-hand operand of the operation (possibly wrapped in a conversion).</param> /// <returns> /// If the operator represents lifted equality, then constant value true if both arguments have constant /// value null, constant value false if exactly one argument has constant value null, and null otherwise. /// If the operator represents lifted inequality, then constant value false if both arguments have constant /// value null, constant value true if exactly one argument has constant value null, and null otherwise. /// </returns> /// <remarks> /// SPEC VIOLATION: according to the spec (section 7.19) constant expressions cannot /// include implicit nullable conversions or nullable subexpressions. However, Dev10 /// specifically folds over lifted == and != (see ExpressionBinder::TryFoldingNullableEquality). /// Dev 10 does do compile-time evaluation of simple lifted operators, but it does so /// in a rewriting pass (see NullableRewriter) - they are not treated as constant values. /// </remarks> private static ConstantValue? TryFoldingNullableEquality(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { if (kind.IsLifted()) { BinaryOperatorKind op = kind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { if (left.Kind == BoundKind.Conversion && right.Kind == BoundKind.Conversion) { BoundConversion leftConv = (BoundConversion)left; BoundConversion rightConv = (BoundConversion)right; ConstantValue? leftConstant = leftConv.Operand.ConstantValue; ConstantValue? rightConstant = rightConv.Operand.ConstantValue; if (leftConstant != null && rightConstant != null) { bool leftIsNull = leftConstant.IsNull; bool rightIsNull = rightConstant.IsNull; if (leftIsNull || rightIsNull) { // IMPL CHANGE: Dev10 raises WRN_NubExprIsConstBool in some cases, but that really doesn't // make sense (why warn that a constant has a constant value?). return (leftIsNull == rightIsNull) == (op == BinaryOperatorKind.Equal) ? ConstantValue.True : ConstantValue.False; } } } } } return null; } // Some binary operators on constants never overflow, regardless of whether the context is checked or not. private static object? FoldNeverOverflowBinaryOperators(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); // Note that we *cannot* do folding on single-precision floats as doubles to preserve precision, // as that would cause incorrect rounding that would be impossible to correct afterwards. switch (kind) { case BinaryOperatorKind.ObjectEqual: if (valueLeft.IsNull) return valueRight.IsNull; if (valueRight.IsNull) return false; break; case BinaryOperatorKind.ObjectNotEqual: if (valueLeft.IsNull) return !valueRight.IsNull; if (valueRight.IsNull) return true; break; case BinaryOperatorKind.DoubleAddition: return valueLeft.DoubleValue + valueRight.DoubleValue; case BinaryOperatorKind.FloatAddition: return valueLeft.SingleValue + valueRight.SingleValue; case BinaryOperatorKind.DoubleSubtraction: return valueLeft.DoubleValue - valueRight.DoubleValue; case BinaryOperatorKind.FloatSubtraction: return valueLeft.SingleValue - valueRight.SingleValue; case BinaryOperatorKind.DoubleMultiplication: return valueLeft.DoubleValue * valueRight.DoubleValue; case BinaryOperatorKind.FloatMultiplication: return valueLeft.SingleValue * valueRight.SingleValue; case BinaryOperatorKind.DoubleDivision: return valueLeft.DoubleValue / valueRight.DoubleValue; case BinaryOperatorKind.FloatDivision: return valueLeft.SingleValue / valueRight.SingleValue; case BinaryOperatorKind.DoubleRemainder: return valueLeft.DoubleValue % valueRight.DoubleValue; case BinaryOperatorKind.FloatRemainder: return valueLeft.SingleValue % valueRight.SingleValue; case BinaryOperatorKind.IntLeftShift: return valueLeft.Int32Value << valueRight.Int32Value; case BinaryOperatorKind.LongLeftShift: return valueLeft.Int64Value << valueRight.Int32Value; case BinaryOperatorKind.UIntLeftShift: return valueLeft.UInt32Value << valueRight.Int32Value; case BinaryOperatorKind.ULongLeftShift: return valueLeft.UInt64Value << valueRight.Int32Value; case BinaryOperatorKind.IntRightShift: case BinaryOperatorKind.NIntRightShift: return valueLeft.Int32Value >> valueRight.Int32Value; case BinaryOperatorKind.LongRightShift: return valueLeft.Int64Value >> valueRight.Int32Value; case BinaryOperatorKind.UIntRightShift: case BinaryOperatorKind.NUIntRightShift: return valueLeft.UInt32Value >> valueRight.Int32Value; case BinaryOperatorKind.ULongRightShift: return valueLeft.UInt64Value >> valueRight.Int32Value; case BinaryOperatorKind.BoolAnd: return valueLeft.BooleanValue & valueRight.BooleanValue; case BinaryOperatorKind.IntAnd: case BinaryOperatorKind.NIntAnd: return valueLeft.Int32Value & valueRight.Int32Value; case BinaryOperatorKind.LongAnd: return valueLeft.Int64Value & valueRight.Int64Value; case BinaryOperatorKind.UIntAnd: case BinaryOperatorKind.NUIntAnd: return valueLeft.UInt32Value & valueRight.UInt32Value; case BinaryOperatorKind.ULongAnd: return valueLeft.UInt64Value & valueRight.UInt64Value; case BinaryOperatorKind.BoolOr: return valueLeft.BooleanValue | valueRight.BooleanValue; case BinaryOperatorKind.IntOr: case BinaryOperatorKind.NIntOr: return valueLeft.Int32Value | valueRight.Int32Value; case BinaryOperatorKind.LongOr: return valueLeft.Int64Value | valueRight.Int64Value; case BinaryOperatorKind.UIntOr: case BinaryOperatorKind.NUIntOr: return valueLeft.UInt32Value | valueRight.UInt32Value; case BinaryOperatorKind.ULongOr: return valueLeft.UInt64Value | valueRight.UInt64Value; case BinaryOperatorKind.BoolXor: return valueLeft.BooleanValue ^ valueRight.BooleanValue; case BinaryOperatorKind.IntXor: case BinaryOperatorKind.NIntXor: return valueLeft.Int32Value ^ valueRight.Int32Value; case BinaryOperatorKind.LongXor: return valueLeft.Int64Value ^ valueRight.Int64Value; case BinaryOperatorKind.UIntXor: case BinaryOperatorKind.NUIntXor: return valueLeft.UInt32Value ^ valueRight.UInt32Value; case BinaryOperatorKind.ULongXor: return valueLeft.UInt64Value ^ valueRight.UInt64Value; case BinaryOperatorKind.LogicalBoolAnd: return valueLeft.BooleanValue && valueRight.BooleanValue; case BinaryOperatorKind.LogicalBoolOr: return valueLeft.BooleanValue || valueRight.BooleanValue; case BinaryOperatorKind.BoolEqual: return valueLeft.BooleanValue == valueRight.BooleanValue; case BinaryOperatorKind.StringEqual: return valueLeft.StringValue == valueRight.StringValue; case BinaryOperatorKind.DecimalEqual: return valueLeft.DecimalValue == valueRight.DecimalValue; case BinaryOperatorKind.FloatEqual: return valueLeft.SingleValue == valueRight.SingleValue; case BinaryOperatorKind.DoubleEqual: return valueLeft.DoubleValue == valueRight.DoubleValue; case BinaryOperatorKind.IntEqual: case BinaryOperatorKind.NIntEqual: return valueLeft.Int32Value == valueRight.Int32Value; case BinaryOperatorKind.LongEqual: return valueLeft.Int64Value == valueRight.Int64Value; case BinaryOperatorKind.UIntEqual: case BinaryOperatorKind.NUIntEqual: return valueLeft.UInt32Value == valueRight.UInt32Value; case BinaryOperatorKind.ULongEqual: return valueLeft.UInt64Value == valueRight.UInt64Value; case BinaryOperatorKind.BoolNotEqual: return valueLeft.BooleanValue != valueRight.BooleanValue; case BinaryOperatorKind.StringNotEqual: return valueLeft.StringValue != valueRight.StringValue; case BinaryOperatorKind.DecimalNotEqual: return valueLeft.DecimalValue != valueRight.DecimalValue; case BinaryOperatorKind.FloatNotEqual: return valueLeft.SingleValue != valueRight.SingleValue; case BinaryOperatorKind.DoubleNotEqual: return valueLeft.DoubleValue != valueRight.DoubleValue; case BinaryOperatorKind.IntNotEqual: case BinaryOperatorKind.NIntNotEqual: return valueLeft.Int32Value != valueRight.Int32Value; case BinaryOperatorKind.LongNotEqual: return valueLeft.Int64Value != valueRight.Int64Value; case BinaryOperatorKind.UIntNotEqual: case BinaryOperatorKind.NUIntNotEqual: return valueLeft.UInt32Value != valueRight.UInt32Value; case BinaryOperatorKind.ULongNotEqual: return valueLeft.UInt64Value != valueRight.UInt64Value; case BinaryOperatorKind.DecimalLessThan: return valueLeft.DecimalValue < valueRight.DecimalValue; case BinaryOperatorKind.FloatLessThan: return valueLeft.SingleValue < valueRight.SingleValue; case BinaryOperatorKind.DoubleLessThan: return valueLeft.DoubleValue < valueRight.DoubleValue; case BinaryOperatorKind.IntLessThan: case BinaryOperatorKind.NIntLessThan: return valueLeft.Int32Value < valueRight.Int32Value; case BinaryOperatorKind.LongLessThan: return valueLeft.Int64Value < valueRight.Int64Value; case BinaryOperatorKind.UIntLessThan: case BinaryOperatorKind.NUIntLessThan: return valueLeft.UInt32Value < valueRight.UInt32Value; case BinaryOperatorKind.ULongLessThan: return valueLeft.UInt64Value < valueRight.UInt64Value; case BinaryOperatorKind.DecimalGreaterThan: return valueLeft.DecimalValue > valueRight.DecimalValue; case BinaryOperatorKind.FloatGreaterThan: return valueLeft.SingleValue > valueRight.SingleValue; case BinaryOperatorKind.DoubleGreaterThan: return valueLeft.DoubleValue > valueRight.DoubleValue; case BinaryOperatorKind.IntGreaterThan: case BinaryOperatorKind.NIntGreaterThan: return valueLeft.Int32Value > valueRight.Int32Value; case BinaryOperatorKind.LongGreaterThan: return valueLeft.Int64Value > valueRight.Int64Value; case BinaryOperatorKind.UIntGreaterThan: case BinaryOperatorKind.NUIntGreaterThan: return valueLeft.UInt32Value > valueRight.UInt32Value; case BinaryOperatorKind.ULongGreaterThan: return valueLeft.UInt64Value > valueRight.UInt64Value; case BinaryOperatorKind.DecimalLessThanOrEqual: return valueLeft.DecimalValue <= valueRight.DecimalValue; case BinaryOperatorKind.FloatLessThanOrEqual: return valueLeft.SingleValue <= valueRight.SingleValue; case BinaryOperatorKind.DoubleLessThanOrEqual: return valueLeft.DoubleValue <= valueRight.DoubleValue; case BinaryOperatorKind.IntLessThanOrEqual: case BinaryOperatorKind.NIntLessThanOrEqual: return valueLeft.Int32Value <= valueRight.Int32Value; case BinaryOperatorKind.LongLessThanOrEqual: return valueLeft.Int64Value <= valueRight.Int64Value; case BinaryOperatorKind.UIntLessThanOrEqual: case BinaryOperatorKind.NUIntLessThanOrEqual: return valueLeft.UInt32Value <= valueRight.UInt32Value; case BinaryOperatorKind.ULongLessThanOrEqual: return valueLeft.UInt64Value <= valueRight.UInt64Value; case BinaryOperatorKind.DecimalGreaterThanOrEqual: return valueLeft.DecimalValue >= valueRight.DecimalValue; case BinaryOperatorKind.FloatGreaterThanOrEqual: return valueLeft.SingleValue >= valueRight.SingleValue; case BinaryOperatorKind.DoubleGreaterThanOrEqual: return valueLeft.DoubleValue >= valueRight.DoubleValue; case BinaryOperatorKind.IntGreaterThanOrEqual: case BinaryOperatorKind.NIntGreaterThanOrEqual: return valueLeft.Int32Value >= valueRight.Int32Value; case BinaryOperatorKind.LongGreaterThanOrEqual: return valueLeft.Int64Value >= valueRight.Int64Value; case BinaryOperatorKind.UIntGreaterThanOrEqual: case BinaryOperatorKind.NUIntGreaterThanOrEqual: return valueLeft.UInt32Value >= valueRight.UInt32Value; case BinaryOperatorKind.ULongGreaterThanOrEqual: return valueLeft.UInt64Value >= valueRight.UInt64Value; case BinaryOperatorKind.UIntDivision: case BinaryOperatorKind.NUIntDivision: return valueLeft.UInt32Value / valueRight.UInt32Value; case BinaryOperatorKind.ULongDivision: return valueLeft.UInt64Value / valueRight.UInt64Value; // MinValue % -1 always overflows at runtime but never at compile time case BinaryOperatorKind.IntRemainder: return (valueRight.Int32Value != -1) ? valueLeft.Int32Value % valueRight.Int32Value : 0; case BinaryOperatorKind.LongRemainder: return (valueRight.Int64Value != -1) ? valueLeft.Int64Value % valueRight.Int64Value : 0; case BinaryOperatorKind.UIntRemainder: case BinaryOperatorKind.NUIntRemainder: return valueLeft.UInt32Value % valueRight.UInt32Value; case BinaryOperatorKind.ULongRemainder: return valueLeft.UInt64Value % valueRight.UInt64Value; } return null; } /// <summary> /// Returns ConstantValue.Bad if, and only if, the resulting string length exceeds <see cref="int.MaxValue"/>. /// </summary> private static ConstantValue? FoldStringConcatenation(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); if (kind == BinaryOperatorKind.StringConcatenation) { Rope leftValue = valueLeft.RopeValue ?? Rope.Empty; Rope rightValue = valueRight.RopeValue ?? Rope.Empty; long newLength = (long)leftValue.Length + (long)rightValue.Length; return (newLength > int.MaxValue) ? ConstantValue.Bad : ConstantValue.CreateFromRope(Rope.Concat(leftValue, rightValue)); } return null; } #nullable disable private static BinaryOperatorKind SyntaxKindToBinaryOperatorKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.MultiplyExpression: return BinaryOperatorKind.Multiplication; case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.DivideExpression: return BinaryOperatorKind.Division; case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.ModuloExpression: return BinaryOperatorKind.Remainder; case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AddExpression: return BinaryOperatorKind.Addition; case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.SubtractExpression: return BinaryOperatorKind.Subtraction; case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.RightShiftExpression: return BinaryOperatorKind.RightShift; case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.LeftShiftExpression: return BinaryOperatorKind.LeftShift; case SyntaxKind.EqualsExpression: return BinaryOperatorKind.Equal; case SyntaxKind.NotEqualsExpression: return BinaryOperatorKind.NotEqual; case SyntaxKind.GreaterThanExpression: return BinaryOperatorKind.GreaterThan; case SyntaxKind.LessThanExpression: return BinaryOperatorKind.LessThan; case SyntaxKind.GreaterThanOrEqualExpression: return BinaryOperatorKind.GreaterThanOrEqual; case SyntaxKind.LessThanOrEqualExpression: return BinaryOperatorKind.LessThanOrEqual; case SyntaxKind.AndAssignmentExpression: case SyntaxKind.BitwiseAndExpression: return BinaryOperatorKind.And; case SyntaxKind.OrAssignmentExpression: case SyntaxKind.BitwiseOrExpression: return BinaryOperatorKind.Or; case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.ExclusiveOrExpression: return BinaryOperatorKind.Xor; case SyntaxKind.LogicalAndExpression: return BinaryOperatorKind.LogicalAnd; case SyntaxKind.LogicalOrExpression: return BinaryOperatorKind.LogicalOr; default: throw ExceptionUtilities.UnexpectedValue(kind); } } private BoundExpression BindIncrementOperator(CSharpSyntaxNode node, ExpressionSyntax operandSyntax, SyntaxToken operatorToken, BindingDiagnosticBag diagnostics) { operandSyntax.CheckDeconstructionCompatibleArgument(diagnostics); BoundExpression operand = BindToNaturalType(BindValue(operandSyntax, diagnostics, BindValueKind.IncrementDecrement), diagnostics); UnaryOperatorKind kind = SyntaxKindToUnaryOperatorKind(node.Kind()); // If the operand is bad, avoid generating cascading errors. if (operand.HasAnyErrors) { // NOTE: no candidate user-defined operators. return new BoundIncrementOperator( node, kind, operand, methodOpt: null, constrainedToTypeOpt: null, Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); } // The operand has to be a variable, property or indexer, so it must have a type. var operandType = operand.Type; Debug.Assert((object)operandType != null); if (operandType.IsDynamic()) { return new BoundIncrementOperator( node, kind.WithType(UnaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), operand, methodOpt: null, constrainedToTypeOpt: null, operandConversion: Conversion.NoConversion, resultConversion: Conversion.NoConversion, resultKind: LookupResultKind.Viable, originalUserDefinedOperatorsOpt: default(ImmutableArray<MethodSymbol>), type: operandType, hasErrors: false); } LookupResultKind resultKind; ImmutableArray<MethodSymbol> originalUserDefinedOperators; var best = this.UnaryOperatorOverloadResolution(kind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); if (!best.HasValue) { ReportUnaryOperatorError(node, diagnostics, operatorToken.Text, operand, resultKind); return new BoundIncrementOperator( node, kind, operand, methodOpt: null, constrainedToTypeOpt: null, Conversion.NoConversion, Conversion.NoConversion, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); } var signature = best.Signature; CheckNativeIntegerFeatureAvailability(signature.Kind, node, diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resultConversion = Conversions.ClassifyConversionFromType(signature.ReturnType, operandType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); bool hasErrors = false; if (!resultConversion.IsImplicit || !resultConversion.IsValid) { GenerateImplicitConversionError(diagnostics, this.Compilation, node, resultConversion, signature.ReturnType, operandType); hasErrors = true; } else { ReportDiagnosticsIfObsolete(diagnostics, resultConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, resultConversion, diagnostics); } if (!hasErrors && operandType.IsVoidPointer()) { Error(diagnostics, ErrorCode.ERR_VoidError, node); hasErrors = true; } Conversion operandConversion = best.Conversion; ReportDiagnosticsIfObsolete(diagnostics, operandConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, operandConversion, diagnostics); return new BoundIncrementOperator( node, signature.Kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), operand, signature.Method, signature.ConstrainedToTypeOpt, operandConversion, resultConversion, resultKind, originalUserDefinedOperators, operandType, hasErrors); } #nullable enable /// <summary> /// Returns false if reported an error, true otherwise. /// </summary> private bool CheckConstraintLanguageVersionAndRuntimeSupportForOperator(SyntaxNode node, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, BindingDiagnosticBag diagnostics) { bool result = true; if (methodOpt?.ContainingType?.IsInterface == true && methodOpt.IsStatic) { if (methodOpt.IsAbstract) { if (constrainedToTypeOpt is not TypeParameterSymbol) { Error(diagnostics, ErrorCode.ERR_BadAbstractStaticMemberAccess, node); return false; } if (Compilation.SourceModule != methodOpt.ContainingModule) { result = CheckFeatureAvailability(node, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, node); return false; } } } else if (methodOpt.Name is WellKnownMemberNames.EqualityOperatorName or WellKnownMemberNames.InequalityOperatorName) { result = CheckFeatureAvailability(node, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); } } return result; } #nullable disable private BoundExpression BindSuppressNullableWarningExpression(PostfixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { var expr = BindExpression(node.Operand, diagnostics); switch (expr.Kind) { case BoundKind.NamespaceExpression: case BoundKind.TypeExpression: Error(diagnostics, ErrorCode.ERR_IllegalSuppression, expr.Syntax); break; default: if (expr.IsSuppressed) { Debug.Assert(node.Operand.SkipParens().GetLastToken().Kind() == SyntaxKind.ExclamationToken); Error(diagnostics, ErrorCode.ERR_DuplicateNullSuppression, expr.Syntax); } break; } return expr.WithSuppression(); } // Based on ExpressionBinder::bindPtrIndirection. private BoundExpression BindPointerIndirectionExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = BindToNaturalType(BindValue(node.Operand, diagnostics, GetUnaryAssignmentKind(node.Kind())), diagnostics); TypeSymbol pointedAtType; bool hasErrors; BindPointerIndirectionExpressionInternal(node, operand, diagnostics, out pointedAtType, out hasErrors); return new BoundPointerIndirectionOperator(node, operand, pointedAtType ?? CreateErrorType(), hasErrors); } private static void BindPointerIndirectionExpressionInternal(CSharpSyntaxNode node, BoundExpression operand, BindingDiagnosticBag diagnostics, out TypeSymbol pointedAtType, out bool hasErrors) { var operandType = operand.Type as PointerTypeSymbol; hasErrors = operand.HasAnyErrors; // This would propagate automatically, but by reading it explicitly we can reduce cascading. if ((object)operandType == null) { pointedAtType = null; if (!hasErrors) { // NOTE: Dev10 actually reports ERR_BadUnaryOp if the operand has Type == null, // but this seems clearer. Error(diagnostics, ErrorCode.ERR_PtrExpected, node); hasErrors = true; } } else { pointedAtType = operandType.PointedAtType; if (pointedAtType.IsVoidType()) { pointedAtType = null; if (!hasErrors) { Error(diagnostics, ErrorCode.ERR_VoidError, node); hasErrors = true; } } } } // Based on ExpressionBinder::bindPtrAddr. private BoundExpression BindAddressOfExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = BindToNaturalType(BindValue(node.Operand, diagnostics, BindValueKind.AddressOf), diagnostics); ReportSuppressionIfNeeded(operand, diagnostics); bool hasErrors = operand.HasAnyErrors; // This would propagate automatically, but by reading it explicitly we can reduce cascading. bool isFixedStatementAddressOfExpression = SyntaxFacts.IsFixedStatementExpression(node); switch (operand) { case BoundLambda _: case UnboundLambda _: { Debug.Assert(hasErrors); return new BoundAddressOfOperator(node, operand, CreateErrorType(), hasErrors: true); } case BoundMethodGroup methodGroup: return new BoundUnconvertedAddressOfOperator(node, methodGroup, hasErrors); } TypeSymbol operandType = operand.Type; Debug.Assert((object)operandType != null, "BindValue should have caught a null operand type"); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); ManagedKind managedKind = operandType.GetManagedKind(ref useSiteInfo); diagnostics.Add(node.Location, useSiteInfo); bool allowManagedAddressOf = Flags.Includes(BinderFlags.AllowManagedAddressOf); if (!allowManagedAddressOf) { if (!hasErrors) { hasErrors = CheckManagedAddr(Compilation, operandType, managedKind, node.Location, diagnostics); } if (!hasErrors) { Symbol accessedLocalOrParameterOpt; if (IsMoveableVariable(operand, out accessedLocalOrParameterOpt) != isFixedStatementAddressOfExpression) { Error(diagnostics, isFixedStatementAddressOfExpression ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedNeeded, node); hasErrors = true; } } } TypeSymbol pointedAtType = managedKind == ManagedKind.Managed && allowManagedAddressOf ? GetSpecialType(SpecialType.System_IntPtr, diagnostics, node) : operandType ?? CreateErrorType(); TypeSymbol pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(pointedAtType)); return new BoundAddressOfOperator(node, operand, pointerType, hasErrors); } /// <summary> /// Checks to see whether an expression is a "moveable" variable according to the spec. Moveable /// variables have underlying memory which may be moved by the runtime. The spec defines anything /// not fixed as moveable and specifies the expressions which are fixed. /// </summary> internal bool IsMoveableVariable(BoundExpression expr, out Symbol accessedLocalOrParameterOpt) { accessedLocalOrParameterOpt = null; while (true) { BoundKind exprKind = expr.Kind; switch (exprKind) { case BoundKind.FieldAccess: case BoundKind.EventAccess: { FieldSymbol fieldSymbol; BoundExpression receiver; if (exprKind == BoundKind.FieldAccess) { BoundFieldAccess fieldAccess = (BoundFieldAccess)expr; fieldSymbol = fieldAccess.FieldSymbol; receiver = fieldAccess.ReceiverOpt; } else { BoundEventAccess eventAccess = (BoundEventAccess)expr; if (!eventAccess.IsUsableAsField || eventAccess.EventSymbol.IsWindowsRuntimeEvent) { return true; } EventSymbol eventSymbol = eventAccess.EventSymbol; fieldSymbol = eventSymbol.AssociatedField; receiver = eventAccess.ReceiverOpt; } if ((object)fieldSymbol == null || fieldSymbol.IsStatic || (object)receiver == null) { return true; } bool receiverIsLValue = CheckValueKind(receiver.Syntax, receiver, BindValueKind.AddressOf, checkingReceiver: false, diagnostics: BindingDiagnosticBag.Discarded); if (!receiverIsLValue) { return true; } // NOTE: type parameters will already have been weeded out, since a // variable of type parameter type has to be cast to an effective // base or interface type before its fields can be accessed and a // conversion isn't an lvalue. if (receiver.Type.IsReferenceType) { return true; } expr = receiver; continue; } case BoundKind.RangeVariable: { // NOTE: there are cases where you can take the address of a range variable. // e.g. from x in new int[3] select *(&x) BoundRangeVariable variableAccess = (BoundRangeVariable)expr; expr = variableAccess.Value; //Check the underlying expression. continue; } case BoundKind.Parameter: { BoundParameter parameterAccess = (BoundParameter)expr; ParameterSymbol parameterSymbol = parameterAccess.ParameterSymbol; accessedLocalOrParameterOpt = parameterSymbol; return parameterSymbol.RefKind != RefKind.None; } case BoundKind.ThisReference: case BoundKind.BaseReference: { accessedLocalOrParameterOpt = this.ContainingMemberOrLambda.EnclosingThisSymbol(); return true; } case BoundKind.Local: { BoundLocal localAccess = (BoundLocal)expr; LocalSymbol localSymbol = localAccess.LocalSymbol; accessedLocalOrParameterOpt = localSymbol; // NOTE: The spec says that this is moveable if it is captured by an anonymous function, // but that will be reported separately and error-recovery is better if we say that // such locals are not moveable. return localSymbol.RefKind != RefKind.None; } case BoundKind.PointerIndirectionOperator: //Covers ->, since the receiver will be one of these. case BoundKind.ConvertedStackAllocExpression: { return false; } case BoundKind.PointerElementAccess: { // C# 7.3: // a variable resulting from a... pointer_element_access of the form P[E] [is fixed] if P // is not a fixed size buffer expression, or if the expression is a fixed size buffer // member_access of the form E.I and E is a fixed variable BoundExpression underlyingExpr = ((BoundPointerElementAccess)expr).Expression; if (underlyingExpr is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { expr = fieldAccess.ReceiverOpt; continue; } return false; } case BoundKind.PropertyAccess: // Never fixed case BoundKind.IndexerAccess: // Never fixed default: { return true; } } } } private BoundExpression BindUnaryOperator(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = BindToNaturalType(BindValue(node.Operand, diagnostics, GetUnaryAssignmentKind(node.Kind())), diagnostics); BoundLiteral constant = BindIntegralMinValConstants(node, operand, diagnostics); return constant ?? BindUnaryOperatorCore(node, node.OperatorToken.Text, operand, diagnostics); } private void ReportSuppressionIfNeeded(BoundExpression expr, BindingDiagnosticBag diagnostics) { if (expr.IsSuppressed) { Error(diagnostics, ErrorCode.ERR_IllegalSuppression, expr.Syntax); } } #nullable enable private BoundExpression BindUnaryOperatorCore(CSharpSyntaxNode node, string operatorText, BoundExpression operand, BindingDiagnosticBag diagnostics) { UnaryOperatorKind kind = SyntaxKindToUnaryOperatorKind(node.Kind()); bool isOperandNullOrNew = operand.IsLiteralNull() || operand.IsImplicitObjectCreation(); if (isOperandNullOrNew) { // Dev10 does not allow unary prefix operators to be applied to the null literal // (or other typeless expressions). Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorText, operand.Display); } // If the operand is bad, avoid generating cascading errors. if (isOperandNullOrNew || operand.Type?.IsErrorType() == true) { // Note: no candidate user-defined operators. return new BoundUnaryOperator(node, kind, operand, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Empty, type: CreateErrorType(), hasErrors: true); } // If the operand is dynamic then we do not attempt to do overload resolution at compile // time; we defer that until runtime. If we did overload resolution then the dynamic // operand would be implicitly convertible to the parameter type of each operator // signature, and therefore every operator would be an applicable candidate. Instead // of changing overload resolution to handle dynamic, we just handle it here and let // overload resolution implement the specification. if (operand.HasDynamicType()) { return new BoundUnaryOperator( syntax: node, operatorKind: kind.WithType(UnaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), operand: operand, constantValueOpt: ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, type: operand.Type!); } LookupResultKind resultKind; ImmutableArray<MethodSymbol> originalUserDefinedOperators; var best = this.UnaryOperatorOverloadResolution(kind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); if (!best.HasValue) { ReportUnaryOperatorError(node, diagnostics, operatorText, operand, resultKind); return new BoundUnaryOperator( node, kind, operand, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); } var signature = best.Signature; var resultOperand = CreateConversion(operand.Syntax, operand, best.Conversion, isCast: false, conversionGroupOpt: null, signature.OperandType, diagnostics); var resultType = signature.ReturnType; UnaryOperatorKind resultOperatorKind = signature.Kind; var resultConstant = FoldUnaryOperator(node, resultOperatorKind, resultOperand, resultType, diagnostics); CheckNativeIntegerFeatureAvailability(resultOperatorKind, node, diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); return new BoundUnaryOperator( node, resultOperatorKind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), resultOperand, resultConstant, signature.Method, signature.ConstrainedToTypeOpt, resultKind, resultType); } private ConstantValue? FoldEnumUnaryOperator( CSharpSyntaxNode syntax, UnaryOperatorKind kind, BoundExpression operand, BindingDiagnosticBag diagnostics) { var underlyingType = operand.Type.GetEnumUnderlyingType()!; BoundExpression newOperand = CreateConversion(operand, underlyingType, diagnostics); // We may have to upconvert the type if it is a byte, sbyte, short, ushort // or nullable of those, because there is no ~ operator var upconvertSpecialType = GetEnumPromotedType(underlyingType.SpecialType); var upconvertType = upconvertSpecialType == underlyingType.SpecialType ? underlyingType : GetSpecialType(upconvertSpecialType, diagnostics, syntax); newOperand = CreateConversion(newOperand, upconvertType, diagnostics); UnaryOperatorKind newKind = kind.Operator().WithType(upconvertSpecialType); var constantValue = FoldUnaryOperator(syntax, newKind, operand, upconvertType, diagnostics); // Convert back to the underlying type if (constantValue != null && !constantValue.IsBad) { // Do an unchecked conversion if bitwise complement var binder = kind.Operator() == UnaryOperatorKind.BitwiseComplement ? this.WithCheckedOrUncheckedRegion(@checked: false) : this; return binder.FoldConstantNumericConversion(syntax, constantValue, underlyingType, diagnostics); } return constantValue; } private ConstantValue? FoldUnaryOperator( CSharpSyntaxNode syntax, UnaryOperatorKind kind, BoundExpression operand, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) { Debug.Assert(operand != null); // UNDONE: report errors when in a checked context. if (operand.HasAnyErrors) { return null; } var value = operand.ConstantValue; if (value == null || value.IsBad) { return value; } if (kind.IsEnum() && !kind.IsLifted()) { return FoldEnumUnaryOperator(syntax, kind, operand, diagnostics); } SpecialType resultType = resultTypeSymbol.SpecialType; var newValue = FoldNeverOverflowUnaryOperator(kind, value); if (newValue != null) { return ConstantValue.Create(newValue, resultType); } try { newValue = FoldNativeIntegerOverflowingUnaryOperator(kind, value); } catch (OverflowException) { if (CheckOverflowAtCompileTime) { Error(diagnostics, ErrorCode.WRN_CompileTimeCheckedOverflow, syntax, resultTypeSymbol); } return null; } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } if (CheckOverflowAtCompileTime) { try { newValue = FoldCheckedIntegralUnaryOperator(kind, value); } catch (OverflowException) { Error(diagnostics, ErrorCode.ERR_CheckedOverflow, syntax); return ConstantValue.Bad; } } else { newValue = FoldUncheckedIntegralUnaryOperator(kind, value); } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } return null; } private static object? FoldNeverOverflowUnaryOperator(UnaryOperatorKind kind, ConstantValue value) { // Note that we do operations on single-precision floats as double-precision. switch (kind) { case UnaryOperatorKind.DecimalUnaryMinus: return -value.DecimalValue; case UnaryOperatorKind.DoubleUnaryMinus: case UnaryOperatorKind.FloatUnaryMinus: return -value.DoubleValue; case UnaryOperatorKind.DecimalUnaryPlus: return +value.DecimalValue; case UnaryOperatorKind.FloatUnaryPlus: case UnaryOperatorKind.DoubleUnaryPlus: return +value.DoubleValue; case UnaryOperatorKind.LongUnaryPlus: return +value.Int64Value; case UnaryOperatorKind.ULongUnaryPlus: return +value.UInt64Value; case UnaryOperatorKind.IntUnaryPlus: case UnaryOperatorKind.NIntUnaryPlus: return +value.Int32Value; case UnaryOperatorKind.UIntUnaryPlus: case UnaryOperatorKind.NUIntUnaryPlus: return +value.UInt32Value; case UnaryOperatorKind.BoolLogicalNegation: return !value.BooleanValue; case UnaryOperatorKind.IntBitwiseComplement: return ~value.Int32Value; case UnaryOperatorKind.LongBitwiseComplement: return ~value.Int64Value; case UnaryOperatorKind.UIntBitwiseComplement: return ~value.UInt32Value; case UnaryOperatorKind.ULongBitwiseComplement: return ~value.UInt64Value; } return null; } private static object? FoldUncheckedIntegralUnaryOperator(UnaryOperatorKind kind, ConstantValue value) { unchecked { switch (kind) { case UnaryOperatorKind.LongUnaryMinus: return -value.Int64Value; case UnaryOperatorKind.IntUnaryMinus: return -value.Int32Value; } } return null; } private static object? FoldCheckedIntegralUnaryOperator(UnaryOperatorKind kind, ConstantValue value) { checked { switch (kind) { case UnaryOperatorKind.LongUnaryMinus: return -value.Int64Value; case UnaryOperatorKind.IntUnaryMinus: return -value.Int32Value; } } return null; } private static object? FoldNativeIntegerOverflowingUnaryOperator(UnaryOperatorKind kind, ConstantValue value) { checked { switch (kind) { case UnaryOperatorKind.NIntUnaryMinus: return -value.Int32Value; case UnaryOperatorKind.NIntBitwiseComplement: case UnaryOperatorKind.NUIntBitwiseComplement: return null; } } return null; } private static UnaryOperatorKind SyntaxKindToUnaryOperatorKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.PreIncrementExpression: return UnaryOperatorKind.PrefixIncrement; case SyntaxKind.PostIncrementExpression: return UnaryOperatorKind.PostfixIncrement; case SyntaxKind.PreDecrementExpression: return UnaryOperatorKind.PrefixDecrement; case SyntaxKind.PostDecrementExpression: return UnaryOperatorKind.PostfixDecrement; case SyntaxKind.UnaryPlusExpression: return UnaryOperatorKind.UnaryPlus; case SyntaxKind.UnaryMinusExpression: return UnaryOperatorKind.UnaryMinus; case SyntaxKind.LogicalNotExpression: return UnaryOperatorKind.LogicalNegation; case SyntaxKind.BitwiseNotExpression: return UnaryOperatorKind.BitwiseComplement; default: throw ExceptionUtilities.UnexpectedValue(kind); } } private static BindValueKind GetBinaryAssignmentKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.SimpleAssignmentExpression: return BindValueKind.Assignable; case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: return BindValueKind.CompoundAssignment; default: return BindValueKind.RValue; } } private static BindValueKind GetUnaryAssignmentKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.PreDecrementExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.PostIncrementExpression: return BindValueKind.IncrementDecrement; case SyntaxKind.AddressOfExpression: Debug.Assert(false, "Should be handled separately."); goto default; default: return BindValueKind.RValue; } } #nullable disable private BoundLiteral BindIntegralMinValConstants(PrefixUnaryExpressionSyntax node, BoundExpression operand, BindingDiagnosticBag diagnostics) { // SPEC: To permit the smallest possible int and long values to be written as decimal integer // SPEC: literals, the following two rules exist: // SPEC: When a decimal-integer-literal with the value 2147483648 and no integer-type-suffix // SPEC: appears as the token immediately following a unary minus operator token, the result is a // SPEC: constant of type int with the value −2147483648. // SPEC: When a decimal-integer-literal with the value 9223372036854775808 and no integer-type-suffix // SPEC: or the integer-type-suffix L or l appears as the token immediately following a unary minus // SPEC: operator token, the result is a constant of type long with the value −9223372036854775808. if (node.Kind() != SyntaxKind.UnaryMinusExpression) { return null; } if (node.Operand != operand.Syntax || operand.Syntax.Kind() != SyntaxKind.NumericLiteralExpression) { return null; } var literal = (LiteralExpressionSyntax)operand.Syntax; var token = literal.Token; if (token.Value is uint) { uint value = (uint)token.Value; if (value != 2147483648U) { return null; } if (token.Text.Contains("u") || token.Text.Contains("U") || token.Text.Contains("l") || token.Text.Contains("L")) { return null; } return new BoundLiteral(node, ConstantValue.Create((int)-2147483648), GetSpecialType(SpecialType.System_Int32, diagnostics, node)); } else if (token.Value is ulong) { var value = (ulong)token.Value; if (value != 9223372036854775808UL) { return null; } if (token.Text.Contains("u") || token.Text.Contains("U")) { return null; } return new BoundLiteral(node, ConstantValue.Create(-9223372036854775808), GetSpecialType(SpecialType.System_Int64, diagnostics, node)); } return null; } private static bool IsDivisionByZero(BinaryOperatorKind kind, ConstantValue valueRight) { Debug.Assert(valueRight != null); switch (kind) { case BinaryOperatorKind.DecimalDivision: case BinaryOperatorKind.DecimalRemainder: return valueRight.DecimalValue == 0.0m; case BinaryOperatorKind.IntDivision: case BinaryOperatorKind.IntRemainder: case BinaryOperatorKind.NIntDivision: case BinaryOperatorKind.NIntRemainder: return valueRight.Int32Value == 0; case BinaryOperatorKind.LongDivision: case BinaryOperatorKind.LongRemainder: return valueRight.Int64Value == 0; case BinaryOperatorKind.UIntDivision: case BinaryOperatorKind.UIntRemainder: case BinaryOperatorKind.NUIntDivision: case BinaryOperatorKind.NUIntRemainder: return valueRight.UInt32Value == 0; case BinaryOperatorKind.ULongDivision: case BinaryOperatorKind.ULongRemainder: return valueRight.UInt64Value == 0; } return false; } private bool IsOperandErrors(CSharpSyntaxNode node, ref BoundExpression operand, BindingDiagnosticBag diagnostics) { switch (operand.Kind) { case BoundKind.UnboundLambda: case BoundKind.Lambda: case BoundKind.MethodGroup: // New in Roslyn - see DevDiv #864740. // operand for an is or as expression cannot be a lambda expression or method group if (!operand.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_LambdaInIsAs, node); } operand = BadExpression(node, operand).MakeCompilerGenerated(); return true; default: if ((object)operand.Type == null && !operand.IsLiteralNull()) { if (!operand.HasAnyErrors) { // Operator 'is' cannot be applied to operand of type '(int, <null>)' Error(diagnostics, ErrorCode.ERR_BadUnaryOp, node, SyntaxFacts.GetText(SyntaxKind.IsKeyword), operand.Display); } operand = BadExpression(node, operand).MakeCompilerGenerated(); return true; } break; } return operand.HasAnyErrors; } private bool IsOperatorErrors(CSharpSyntaxNode node, TypeSymbol operandType, BoundTypeExpression typeExpression, BindingDiagnosticBag diagnostics) { var targetType = typeExpression.Type; // The native compiler allows "x is C" where C is a static class. This // is strictly illegal according to the specification (see the section // called "Referencing Static Class Types".) To retain compatibility we // allow it, but when /warn:5 or higher we break with the native // compiler and turn this into a warning. if (targetType.IsStatic) { Error(diagnostics, ErrorCode.WRN_StaticInAsOrIs, node, targetType); } if ((object)operandType != null && operandType.IsPointerOrFunctionPointer() || targetType.IsPointerOrFunctionPointer()) { // operand for an is or as expression cannot be of pointer type Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, node); return true; } return targetType.TypeKind == TypeKind.Error; } protected static bool IsUnderscore(ExpressionSyntax node) => node is IdentifierNameSyntax name && name.Identifier.IsUnderscoreToken(); private BoundExpression BindIsOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { var resultType = (TypeSymbol)GetSpecialType(SpecialType.System_Boolean, diagnostics, node); var operand = BindRValueWithoutTargetType(node.Left, diagnostics); var operandHasErrors = IsOperandErrors(node, ref operand, diagnostics); // try binding as a type, but back off to binding as an expression if that does not work. bool wasUnderscore = IsUnderscore(node.Right); if (!tryBindAsType(node.Right, diagnostics, out BindingDiagnosticBag isTypeDiagnostics, out BoundTypeExpression typeExpression) && !wasUnderscore && ((CSharpParseOptions)node.SyntaxTree.Options).IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching)) { // it did not bind as a type; try binding as a constant expression pattern var isPatternDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); if ((object)operand.Type == null) { if (!operandHasErrors) { isPatternDiagnostics.Add(ErrorCode.ERR_BadPatternExpression, node.Left.Location, operand.Display); } operand = ToBadExpression(operand); } bool hasErrors = node.Right.HasErrors; var convertedExpression = BindExpressionForPattern(operand.Type, node.Right, ref hasErrors, isPatternDiagnostics, out var constantValueOpt, out var wasExpression); if (wasExpression) { hasErrors |= constantValueOpt is null; isTypeDiagnostics.Free(); diagnostics.AddRangeAndFree(isPatternDiagnostics); var boundConstantPattern = new BoundConstantPattern( node.Right, convertedExpression, constantValueOpt ?? ConstantValue.Bad, operand.Type, convertedExpression.Type ?? operand.Type, hasErrors) #pragma warning disable format { WasCompilerGenerated = true }; #pragma warning restore format return MakeIsPatternExpression(node, operand, boundConstantPattern, resultType, operandHasErrors, diagnostics); } isPatternDiagnostics.Free(); } diagnostics.AddRangeAndFree(isTypeDiagnostics); var targetTypeWithAnnotations = typeExpression.TypeWithAnnotations; var targetType = typeExpression.Type; if (targetType.IsReferenceType && targetTypeWithAnnotations.NullableAnnotation.IsAnnotated()) { Error(diagnostics, ErrorCode.ERR_IsNullableType, node.Right, targetType); operandHasErrors = true; } var targetTypeKind = targetType.TypeKind; if (operandHasErrors || IsOperatorErrors(node, operand.Type, typeExpression, diagnostics)) { return new BoundIsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } if (wasUnderscore && ((CSharpParseOptions)node.SyntaxTree.Options).IsFeatureEnabled(MessageID.IDS_FeatureRecursivePatterns)) { diagnostics.Add(ErrorCode.WRN_IsTypeNamedUnderscore, node.Right.Location, typeExpression.AliasOpt ?? (Symbol)targetType); } // Is and As operator should have null ConstantValue as they are not constant expressions. // However we perform analysis of is/as expressions at bind time to detect if the expression // will always evaluate to a constant to generate warnings (always true/false/null). // We also need this analysis result during rewrite to optimize away redundant isinst instructions. // We store the conversion from expression's operand type to target type to enable these // optimizations during is/as operator rewrite. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (operand.ConstantValue == ConstantValue.Null || operand.Kind == BoundKind.MethodGroup || operand.Type.IsVoidType()) { // warning for cases where the result is always false: // (a) "null is TYPE" OR operand evaluates to null // (b) operand is a MethodGroup // (c) operand is of void type // NOTE: Dev10 violates the SPEC for case (c) above and generates // NOTE: an error ERR_NoExplicitBuiltinConv if the target type // NOTE: is an open type. According to the specification, the result // NOTE: is always false, but no compile time error occurs. // NOTE: We follow the specification and generate WRN_IsAlwaysFalse // NOTE: instead of an error. // NOTE: See Test SyntaxBinderTests.TestIsOperatorWithTypeParameter Error(diagnostics, ErrorCode.WRN_IsAlwaysFalse, node, targetType); Conversion conv = Conversions.ClassifyConversionFromExpression(operand, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); return new BoundIsOperator(node, operand, typeExpression, conv, resultType); } if (targetTypeKind == TypeKind.Dynamic) { // warning for dynamic target type Error(diagnostics, ErrorCode.WRN_IsDynamicIsConfusing, node, node.OperatorToken.Text, targetType.Name, GetSpecialType(SpecialType.System_Object, diagnostics, node).Name // a pretty way of getting the string "Object" ); } var operandType = operand.Type; Debug.Assert((object)operandType != null); if (operandType.TypeKind == TypeKind.Dynamic) { // if operand has a dynamic type, we do the same thing as though it were an object operandType = GetSpecialType(SpecialType.System_Object, diagnostics, node); } Conversion conversion = Conversions.ClassifyBuiltInConversion(operandType, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); ReportIsOperatorConstantWarnings(node, diagnostics, operandType, targetType, conversion.Kind, operand.ConstantValue); return new BoundIsOperator(node, operand, typeExpression, conversion, resultType); bool tryBindAsType( ExpressionSyntax possibleType, BindingDiagnosticBag diagnostics, out BindingDiagnosticBag bindAsTypeDiagnostics, out BoundTypeExpression boundType) { bindAsTypeDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); TypeWithAnnotations targetTypeWithAnnotations = BindType(possibleType, bindAsTypeDiagnostics, out AliasSymbol alias); TypeSymbol targetType = targetTypeWithAnnotations.Type; boundType = new BoundTypeExpression(possibleType, alias, targetTypeWithAnnotations); return !(targetType?.IsErrorType() == true && bindAsTypeDiagnostics.HasAnyResolvedErrors()); } } private static void ReportIsOperatorConstantWarnings( CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) { // NOTE: Even though BoundIsOperator and BoundAsOperator will always have no ConstantValue // NOTE: (they are non-constant expressions according to Section 7.19 of the specification), // NOTE: we want to perform constant analysis of is/as expressions to generate warnings if the // NOTE: expression will always be true/false/null. ConstantValue constantValue = GetIsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); if (constantValue != null) { Debug.Assert(constantValue == ConstantValue.True || constantValue == ConstantValue.False); ErrorCode errorCode = constantValue == ConstantValue.True ? ErrorCode.WRN_IsAlwaysTrue : ErrorCode.WRN_IsAlwaysFalse; Error(diagnostics, errorCode, syntax, targetType); } } internal static ConstantValue GetIsOperatorConstantResult( TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue, bool operandCouldBeNull = true) { Debug.Assert((object)targetType != null); // SPEC: The result of the operation depends on D and T as follows: // SPEC: 1) If T is a reference type, the result is true if D and T are the same type, if D is a reference type and // SPEC: an implicit reference conversion from D to T exists, or if D is a value type and a boxing conversion from D to T exists. // SPEC: 2) If T is a nullable type, the result is true if D is the underlying type of T. // SPEC: 3) If T is a non-nullable value type, the result is true if D and T are the same type. // SPEC: 4) Otherwise, the result is false. // NOTE: The language specification talks about the runtime evaluation of the is operation. // NOTE: However, we are interested in computing the compile time constant value for the expression. // NOTE: Even though BoundIsOperator and BoundAsOperator will always have no ConstantValue // NOTE: (they are non-constant expressions according to Section 7.19 of the specification), // NOTE: we want to perform constant analysis of is/as expressions during binding to generate warnings // NOTE: (always true/false/null) and during rewriting for optimized codegen. // NOTE: // NOTE: Because the heuristic presented here is used to change codegen, it must be conservative. It is acceptable // NOTE: for us to fail to report a warning in cases where humans could logically deduce that the operator will // NOTE: always return false. It is not acceptable to inaccurately warn that the operator will always return false // NOTE: if there are cases where it might succeed. // NOTE: // NOTE: These same heuristics are also used in pattern-matching to determine if an expression of the form // NOTE: `e is T x` is permitted. It is an error if `e` cannot be of type `T` according to this method // NOTE: returning ConstantValue.False. // NOTE: The heuristics are also used to determine if a `case T1 x1:` is subsumed by // NOTE: some previous `case T2 x2:` in a switch statement. For that purpose operandType is T1, targetType is T2, // NOTE: and operandCouldBeNull is false; the former subsumes the latter if this method returns ConstantValue.True. // NOTE: Since the heuristic is now used to produce errors in pattern-matching, making it more accurate in the // NOTE: future could be a breaking change. // To begin our heuristic: if the operand is literal null then we automatically return that the // result is false. You might think that we can simply check to see if the conversion is // ConversionKind.NullConversion, but "null is T" for a type parameter T is actually classified // as an implicit reference conversion if T is constrained to reference types. Rather // than deal with all those special cases we can simply bail out here. if (operandConstantValue == ConstantValue.Null) { return ConstantValue.False; } Debug.Assert((object)operandType != null); operandCouldBeNull = operandCouldBeNull && operandType.CanContainNull() && // a non-nullable value type is never null (operandConstantValue == null || operandConstantValue == ConstantValue.Null); // a non-null constant is never null switch (conversionKind) { case ConversionKind.NoConversion: // Oddly enough, "x is T" can be true even if there is no conversion from x to T! // // Scenario 1: Type parameter compared to System.Enum. // // bool M1<X>(X x) where X : struct { return x is Enum; } // // There is no conversion from X to Enum, not even an explicit conversion. But // nevertheless, X could be constructed as an enumerated type. // However, we can sometimes know that the result will be false. // // Scenario 2a: Constrained type parameter compared to reference type. // // bool M2a<X>(X x) where X : struct { return x is string; } // // We know that X, constrained to struct, will never be string. // // Scenario 2b: Reference type compared to constrained type parameter. // // bool M2b<X>(string x) where X : struct { return x is X; } // // We know that string will never be X, constrained to struct. // // Scenario 3: Value type compared to type parameter. // // bool M3<T>(int x) { return x is T; } // // There is no conversion from int to T, but T could nevertheless be int. // // Scenario 4: Constructed type compared to open type // // bool M4<T>(C<int> x) { return x is C<T>; } // // There is no conversion from C<int> to C<T>, but nevertheless, T might be int. // // Scenario 5: Open type compared to constructed type: // // bool M5<X>(C<X> x) { return x is C<int>); // // Again, X could be int. // // We could then go on to get more complicated. For example, // // bool M6<X>(C<X> x) where X : struct { return x is C<string>; } // // We know that C<X> is never convertible to C<string> no matter what // X is. Or: // // bool M7<T>(Dictionary<int, int> x) { return x is List<T>; } // // We know that no matter what T is, the conversion will never succeed. // // As noted above, we must be conservative. We follow the lead of the native compiler, // which uses the following algorithm: // // * If neither type is open and there is no conversion then the result is always false: if (!operandType.ContainsTypeParameter() && !targetType.ContainsTypeParameter()) { return ConstantValue.False; } // * Otherwise, at least one of them is of an open type. If the operand is of value type // and the target is a class type other than System.Enum, or vice versa, then we are // in scenario 2, not scenario 1, and can correctly deduce that the result is false. if (operandType.IsValueType && targetType.IsClassType() && targetType.SpecialType != SpecialType.System_Enum || targetType.IsValueType && operandType.IsClassType() && operandType.SpecialType != SpecialType.System_Enum) { return ConstantValue.False; } // * Otherwise, if the other type is a restricted type, we know no conversion is possible. if (targetType.IsRestrictedType() || operandType.IsRestrictedType()) { return ConstantValue.False; } // * Otherwise, we give up. Though there are other situations in which we can deduce that // the result will always be false, such as scenarios 6 and 7, but we do not attempt // to deduce this. // CONSIDER: we could use TypeUnification.CanUnify to do additional compile-time checking. return null; case ConversionKind.ImplicitNumeric: case ConversionKind.ExplicitNumeric: case ConversionKind.ImplicitEnumeration: // case ConversionKind.ExplicitEnumeration: // Handled separately below. case ConversionKind.ImplicitConstant: case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: case ConversionKind.IntPtr: case ConversionKind.ExplicitTuple: case ConversionKind.ImplicitTuple: // Consider all the cases where we know that "x is T" must be false just from // the conversion classification. // // If we have "x is T" and the conversion from x to T is numeric or enum then the result must be false. // // If we have "null is T" then obviously that must be false. // // If we have "1 is long" then that must be false. (If we have "1 is int" then it is an identity conversion, // not an implicit constant conversion. // // User-defined and IntPtr conversions are always false for "is". return ConstantValue.False; case ConversionKind.ExplicitEnumeration: // Enum-to-enum conversions should be treated the same as unsuccessful struct-to-struct // conversions (i.e. make allowances for type unification, etc) if (operandType.IsEnumType() && targetType.IsEnumType()) { goto case ConversionKind.NoConversion; } return ConstantValue.False; case ConversionKind.ExplicitNullable: // An explicit nullable conversion is a conversion of one of the following forms: // // 1) X? --> Y?, where X --> Y is an explicit conversion. (If X --> Y is an implicit // conversion then X? --> Y? is an implicit nullable conversion.) In this case we // know that "X? is Y?" must be false because either X? is null, or we have an // explicit conversion from struct type X to struct type Y, and so X is never of type Y.) // // 2) X --> Y?, where again, X --> Y is an explicit conversion. By the same reasoning // as in case 1, this must be false. if (targetType.IsNullableType()) { return ConstantValue.False; } Debug.Assert(operandType.IsNullableType()); // 3) X? --> X. In this case, this is just a different way of writing "x != null". // We only know what the result will be if the input is known not to be null. if (Conversions.HasIdentityConversion(operandType.GetNullableUnderlyingType(), targetType)) { return operandCouldBeNull ? null : ConstantValue.True; } // 4) X? --> Y where the conversion X --> Y is an implicit or explicit value type conversion. // "X? is Y" again must be false. return ConstantValue.False; case ConversionKind.ImplicitReference: return operandCouldBeNull ? null : ConstantValue.True; case ConversionKind.ExplicitReference: case ConversionKind.Unboxing: // In these three cases, the expression type must be a reference type. Therefore, // the result cannot be determined. The expression could be null or of the wrong type, // resulting in false, or it could be a non-null reference to the appropriate type, // resulting in true. return null; case ConversionKind.Identity: // The result of "x is T" can be statically determined to be true if x is an expression // of non-nullable value type T. If x is of reference or nullable value type then // we cannot know, because again, the expression value could be null or it could be good. // If it is of pointer type then we have already given an error. return operandCouldBeNull ? null : ConstantValue.True; case ConversionKind.Boxing: // A boxing conversion might be a conversion: // // * From a non-nullable value type to a reference type // * From a nullable value type to a reference type // * From a type parameter that *could* be a value type under construction // to a reference type // // In the first case we know that the conversion will always succeed and that the // operand is never null, and therefore "is" will always result in true. // // In the second two cases we do not know; either the nullable value type could be // null, or the type parameter could be constructed with a reference type, and it // could be null. return operandCouldBeNull ? null : ConstantValue.True; case ConversionKind.ImplicitNullable: // We have "x is T" in one of the following situations: // 1) x is of type X and T is X?. The value is always true. // 2) x is of type X and T is Y? where X is convertible to Y via an implicit numeric conversion. Eg, // x is of type int and T is decimal?. The value is always false. // 3) x is of type X? and T is Y? where X is convertible to Y via an implicit numeric conversion. // The value is always false. Debug.Assert(targetType.IsNullableType()); return operandType.Equals(targetType.GetNullableUnderlyingType(), TypeCompareKind.AllIgnoreOptions) ? ConstantValue.True : ConstantValue.False; default: case ConversionKind.ImplicitDynamic: case ConversionKind.ExplicitDynamic: case ConversionKind.ExplicitPointerToInteger: case ConversionKind.ExplicitPointerToPointer: case ConversionKind.ImplicitPointerToVoid: case ConversionKind.ExplicitIntegerToPointer: case ConversionKind.ImplicitNullToPointer: case ConversionKind.AnonymousFunction: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.MethodGroup: // We've either replaced Dynamic with Object, or already bailed out with an error. throw ExceptionUtilities.UnexpectedValue(conversionKind); } } private BoundExpression BindAsOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { var operand = BindRValueWithoutTargetType(node.Left, diagnostics); AliasSymbol alias; TypeWithAnnotations targetTypeWithAnnotations = BindType(node.Right, diagnostics, out alias); TypeSymbol targetType = targetTypeWithAnnotations.Type; var typeExpression = new BoundTypeExpression(node.Right, alias, targetTypeWithAnnotations); var targetTypeKind = targetType.TypeKind; var resultType = targetType; // Is and As operator should have null ConstantValue as they are not constant expressions. // However we perform analysis of is/as expressions at bind time to detect if the expression // will always evaluate to a constant to generate warnings (always true/false/null). // We also need this analysis result during rewrite to optimize away redundant isinst instructions. // We store the conversion kind from expression's operand type to target type to enable these // optimizations during is/as operator rewrite. switch (operand.Kind) { case BoundKind.UnboundLambda: case BoundKind.Lambda: case BoundKind.MethodGroup: // New in Roslyn - see DevDiv #864740. // operand for an is or as expression cannot be a lambda expression or method group if (!operand.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_LambdaInIsAs, node); } return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: if ((object)operand.Type == null) { Error(diagnostics, ErrorCode.ERR_TypelessTupleInAs, node); return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } break; } if (operand.HasAnyErrors || targetTypeKind == TypeKind.Error) { // If either operand is bad or target type has errors, bail out preventing more cascading errors. return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } if (targetType.IsReferenceType && targetTypeWithAnnotations.NullableAnnotation.IsAnnotated()) { Error(diagnostics, ErrorCode.ERR_AsNullableType, node.Right, targetType); return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } else if (!targetType.IsReferenceType && !targetType.IsNullableType()) { // SPEC: In an operation of the form E as T, E must be an expression and T must be a // SPEC: reference type, a type parameter known to be a reference type, or a nullable type. if (targetTypeKind == TypeKind.TypeParameter) { Error(diagnostics, ErrorCode.ERR_AsWithTypeVar, node, targetType); } else if (targetTypeKind == TypeKind.Pointer || targetTypeKind == TypeKind.FunctionPointer) { Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, node); } else { Error(diagnostics, ErrorCode.ERR_AsMustHaveReferenceType, node, targetType); } return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } // The C# specification states in the section called // "Referencing Static Class Types" that it is always // illegal to use "as" with a static type. The // native compiler actually allows "null as C" for // a static type C to be an expression of type C. // It also allows "someObject as C" if "someObject" // is of type object. To retain compatibility we // allow it, but when /warn:5 or higher we break with the native // compiler and turn this into a warning. if (targetType.IsStatic) { Error(diagnostics, ErrorCode.WRN_StaticInAsOrIs, node, targetType); } if (operand.IsLiteralNull()) { // We do not want to warn for the case "null as TYPE" where the null // is a literal, because the user might be saying it to cause overload resolution // to pick a particular method return new BoundAsOperator(node, operand, typeExpression, Conversion.NullLiteral, resultType); } if (operand.IsLiteralDefault()) { operand = new BoundDefaultExpression(operand.Syntax, targetType: null, constantValueOpt: ConstantValue.Null, type: GetSpecialType(SpecialType.System_Object, diagnostics, node)); } var operandType = operand.Type; Debug.Assert((object)operandType != null); var operandTypeKind = operandType.TypeKind; Debug.Assert(!targetType.IsPointerOrFunctionPointer(), "Should have been caught above"); if (operandType.IsPointerOrFunctionPointer()) { // operand for an is or as expression cannot be of pointer type Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, node); return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } if (operandTypeKind == TypeKind.Dynamic) { // if operand has a dynamic type, we do the same thing as though it were an object operandType = GetSpecialType(SpecialType.System_Object, diagnostics, node); operandTypeKind = operandType.TypeKind; } if (targetTypeKind == TypeKind.Dynamic) { // for "as dynamic", we do the same thing as though it were an "as object" targetType = GetSpecialType(SpecialType.System_Object, diagnostics, node); targetTypeKind = targetType.TypeKind; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyBuiltInConversion(operandType, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); bool hasErrors = ReportAsOperatorConversionDiagnostics(node, diagnostics, this.Compilation, operandType, targetType, conversion.Kind, operand.ConstantValue); return new BoundAsOperator(node, operand, typeExpression, conversion, resultType, hasErrors); } private static bool ReportAsOperatorConversionDiagnostics( CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, CSharpCompilation compilation, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) { // SPEC: In an operation of the form E as T, E must be an expression and T must be a reference type, // SPEC: a type parameter known to be a reference type, or a nullable type. // SPEC: Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs: // SPEC: • An identity (§6.1.1), implicit nullable (§6.1.4), implicit reference (§6.1.6), boxing (§6.1.7), // SPEC: explicit nullable (§6.2.3), explicit reference (§6.2.4), or unboxing (§6.2.5) conversion exists // SPEC: from E to T. // SPEC: • The type of E or T is an open type. // SPEC: • E is the null literal. // SPEC VIOLATION: The specification contains an error in the list of legal conversions above. // SPEC VIOLATION: If we have "class C<T, U> where T : U where U : class" then there is // SPEC VIOLATION: an implicit conversion from T to U, but it is not an identity, reference or // SPEC VIOLATION: boxing conversion. It will be one of those at runtime, but at compile time // SPEC VIOLATION: we do not know which, and therefore cannot classify it as any of those. // SPEC VIOLATION: See Microsoft.CodeAnalysis.CSharp.UnitTests.SyntaxBinderTests.TestAsOperator_SpecErrorCase() test for an example. // SPEC VIOLATION: The specification also unintentionally allows the case where requirement 2 above: // SPEC VIOLATION: "The type of E or T is an open type" is true, but type of E is void type, i.e. T is an open type. // SPEC VIOLATION: Dev10 compiler correctly generates an error for this case and we will maintain compatibility. bool hasErrors = false; switch (conversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: case ConversionKind.Identity: case ConversionKind.ExplicitNullable: case ConversionKind.ExplicitReference: case ConversionKind.Unboxing: break; default: // Generate an error if there is no possible legal conversion and both the operandType // and the targetType are closed types OR operandType is void type, otherwise we need a runtime check if (!operandType.ContainsTypeParameter() && !targetType.ContainsTypeParameter() || operandType.IsVoidType()) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, operandType, targetType); Error(diagnostics, ErrorCode.ERR_NoExplicitBuiltinConv, node, distinguisher.First, distinguisher.Second); hasErrors = true; } break; } if (!hasErrors) { ReportAsOperatorConstantWarnings(node, diagnostics, operandType, targetType, conversionKind, operandConstantValue); } return hasErrors; } private static void ReportAsOperatorConstantWarnings( CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) { // NOTE: Even though BoundIsOperator and BoundAsOperator will always have no ConstantValue // NOTE: (they are non-constant expressions according to Section 7.19 of the specification), // NOTE: we want to perform constant analysis of is/as expressions to generate warnings if the // NOTE: expression will always be true/false/null. ConstantValue constantValue = GetAsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); if (constantValue != null) { Debug.Assert(constantValue.IsNull); Error(diagnostics, ErrorCode.WRN_AlwaysNull, node, targetType); } } internal static ConstantValue GetAsOperatorConstantResult(TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) { // NOTE: Even though BoundIsOperator and BoundAsOperator will always have no ConstantValue // NOTE: (they are non-constant expressions according to Section 7.19 of the specification), // NOTE: we want to perform constant analysis of is/as expressions during binding to generate warnings (always true/false/null) // NOTE: and during rewriting for optimized codegen. ConstantValue isOperatorConstantResult = GetIsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); if (isOperatorConstantResult != null && !isOperatorConstantResult.BooleanValue) { return ConstantValue.Null; } return null; } private BoundExpression GenerateNullCoalescingBadBinaryOpsError(BinaryExpressionSyntax node, BoundExpression leftOperand, BoundExpression rightOperand, Conversion leftConversion, BindingDiagnosticBag diagnostics) { Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, SyntaxFacts.GetText(node.OperatorToken.Kind()), leftOperand.Display, rightOperand.Display); leftOperand = BindToTypeForErrorRecovery(leftOperand); rightOperand = BindToTypeForErrorRecovery(rightOperand); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, leftConversion, BoundNullCoalescingOperatorResultKind.NoCommonType, CreateErrorType(), hasErrors: true); } private BoundExpression BindNullCoalescingOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { var leftOperand = BindValue(node.Left, diagnostics, BindValueKind.RValue); leftOperand = BindToNaturalType(leftOperand, diagnostics); var rightOperand = BindValue(node.Right, diagnostics, BindValueKind.RValue); // If either operand is bad, bail out preventing more cascading errors if (leftOperand.HasAnyErrors || rightOperand.HasAnyErrors) { leftOperand = BindToTypeForErrorRecovery(leftOperand); rightOperand = BindToTypeForErrorRecovery(rightOperand); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, Conversion.NoConversion, BoundNullCoalescingOperatorResultKind.NoCommonType, CreateErrorType(), hasErrors: true); } // The specification does not permit the left hand side to be a default literal if (leftOperand.IsLiteralDefault()) { Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, node.OperatorToken.Text, "default"); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, Conversion.NoConversion, BoundNullCoalescingOperatorResultKind.NoCommonType, CreateErrorType(), hasErrors: true); } // SPEC: The type of the expression a ?? b depends on which implicit conversions are available // SPEC: between the types of the operands. In order of preference, the type of a ?? b is A0, A, or B, // SPEC: where A is the type of a, B is the type of b (provided that b has a type), // SPEC: and A0 is the underlying type of A if A is a nullable type, or A otherwise. TypeSymbol optLeftType = leftOperand.Type; // "A" TypeSymbol optRightType = rightOperand.Type; // "B" bool isLeftNullable = (object)optLeftType != null && optLeftType.IsNullableType(); TypeSymbol optLeftType0 = isLeftNullable ? // "A0" optLeftType.GetNullableUnderlyingType() : optLeftType; // SPEC: The left hand side must be either the null literal or it must have a type. Lambdas and method groups do not have a type, // SPEC: so using one is an error. if (leftOperand.Kind == BoundKind.UnboundLambda || leftOperand.Kind == BoundKind.MethodGroup) { return GenerateNullCoalescingBadBinaryOpsError(node, leftOperand, rightOperand, Conversion.NoConversion, diagnostics); } // SPEC: Otherwise, if A exists and is a non-nullable value type, a compile-time error occurs. First we check for the pre-C# 8.0 // SPEC: condition, to ensure that we don't allow previously illegal code in old language versions. if ((object)optLeftType != null && !optLeftType.IsReferenceType && !isLeftNullable) { // Prior to C# 8.0, the spec said that the left type must be either a reference type or a nullable value type. This was relaxed // with C# 8.0, so if the feature is not enabled then issue a diagnostic and return if (!optLeftType.IsValueType) { CheckFeatureAvailability(node, MessageID.IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator, diagnostics); } else { return GenerateNullCoalescingBadBinaryOpsError(node, leftOperand, rightOperand, Conversion.NoConversion, diagnostics); } } // SPEC: If b is a dynamic expression, the result is dynamic. At runtime, a is first // SPEC: evaluated. If a is not null, a is converted to a dynamic type, and this becomes // SPEC: the result. Otherwise, b is evaluated, and the outcome becomes the result. // // Note that there is no runtime dynamic dispatch since comparison with null is not a dynamic operation. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if ((object)optRightType != null && optRightType.IsDynamic()) { var leftConversion = Conversions.ClassifyConversionFromExpression(leftOperand, GetSpecialType(SpecialType.System_Object, diagnostics, node), ref useSiteInfo); rightOperand = BindToNaturalType(rightOperand, diagnostics); diagnostics.Add(node, useSiteInfo); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, leftConversion, BoundNullCoalescingOperatorResultKind.RightDynamicType, optRightType); } // SPEC: Otherwise, if A exists and is a nullable type and an implicit conversion exists from b to A0, // SPEC: the result type is A0. At run-time, a is first evaluated. If a is not null, // SPEC: a is unwrapped to type A0, and this becomes the result. // SPEC: Otherwise, b is evaluated and converted to type A0, and this becomes the result. if (isLeftNullable) { var rightConversion = Conversions.ClassifyImplicitConversionFromExpression(rightOperand, optLeftType0, ref useSiteInfo); if (rightConversion.Exists) { var leftConversion = Conversions.ClassifyConversionFromExpression(leftOperand, optLeftType0, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); var convertedRightOperand = CreateConversion(rightOperand, rightConversion, optLeftType0, diagnostics); return new BoundNullCoalescingOperator(node, leftOperand, convertedRightOperand, leftConversion, BoundNullCoalescingOperatorResultKind.LeftUnwrappedType, optLeftType0); } } // SPEC: Otherwise, if A exists and an implicit conversion exists from b to A, the result type is A. // SPEC: At run-time, a is first evaluated. If a is not null, a becomes the result. // SPEC: Otherwise, b is evaluated and converted to type A, and this becomes the result. if ((object)optLeftType != null) { var rightConversion = Conversions.ClassifyImplicitConversionFromExpression(rightOperand, optLeftType, ref useSiteInfo); if (rightConversion.Exists) { var convertedRightOperand = CreateConversion(rightOperand, rightConversion, optLeftType, diagnostics); var leftConversion = Conversion.Identity; diagnostics.Add(node, useSiteInfo); return new BoundNullCoalescingOperator(node, leftOperand, convertedRightOperand, leftConversion, BoundNullCoalescingOperatorResultKind.LeftType, optLeftType); } } // SPEC: Otherwise, if b has a type B and an implicit conversion exists from a to B, // SPEC: the result type is B. At run-time, a is first evaluated. If a is not null, // SPEC: a is unwrapped to type A0 (if A exists and is nullable) and converted to type B, // SPEC: and this becomes the result. Otherwise, b is evaluated and becomes the result. // SPEC VIOLATION: Native compiler violates the specification here and implements this part based on // SPEC VIOLATION: whether A is a nullable type or not. // SPEC VIOLATION: We will maintain compatibility with the native compiler and do the same. // SPEC VIOLATION: Following SPEC PROPOSAL states the current implementations in both compilers: // SPEC PROPOSAL: Otherwise, if A exists and is a nullable type and if b has a type B and // SPEC PROPOSAL: an implicit conversion exists from A0 to B, the result type is B. // SPEC PROPOSAL: At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 // SPEC PROPOSAL: and converted to type B, and this becomes the result. // SPEC PROPOSAL: Otherwise, b is evaluated and becomes the result. // SPEC PROPOSAL: Otherwise, if A does not exist or is a non-nullable type and if b has a type B and // SPEC PROPOSAL: an implicit conversion exists from a to B, the result type is B. // SPEC PROPOSAL: At run-time, a is first evaluated. If a is not null, a is converted to type B, // SPEC PROPOSAL: and this becomes the result. Otherwise, b is evaluated and becomes the result. // See test CodeGenTests.TestNullCoalescingOperatorWithNullableConversions for an example. if ((object)optRightType != null) { rightOperand = BindToNaturalType(rightOperand, diagnostics); Conversion leftConversion; BoundNullCoalescingOperatorResultKind resultKind; if (isLeftNullable) { // This is the SPEC VIOLATION case. // Note that at runtime we need two conversions on the left operand: // 1) Explicit nullable conversion from leftOperand to optLeftType0 and // 2) Implicit conversion from optLeftType0 to optRightType. // We just store the second conversion in the bound node and insert the first conversion during rewriting // the null coalescing operator. See method LocalRewriter.GetConvertedLeftForNullCoalescingOperator. leftConversion = Conversions.ClassifyImplicitConversionFromType(optLeftType0, optRightType, ref useSiteInfo); resultKind = BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType; } else { leftConversion = Conversions.ClassifyImplicitConversionFromExpression(leftOperand, optRightType, ref useSiteInfo); resultKind = BoundNullCoalescingOperatorResultKind.RightType; } if (leftConversion.Exists) { if (!leftConversion.IsValid) { // CreateConversion here to generate diagnostics. if (isLeftNullable) { var conversion = Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, leftConversion); var strippedLeftOperand = CreateConversion(leftOperand, conversion, optLeftType0, diagnostics); leftOperand = CreateConversion(strippedLeftOperand, leftConversion, optRightType, diagnostics); } else { leftOperand = CreateConversion(leftOperand, leftConversion, optRightType, diagnostics); } Debug.Assert(leftOperand.HasAnyErrors); } else { ReportDiagnosticsIfObsolete(diagnostics, leftConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, leftConversion, diagnostics); } diagnostics.Add(node, useSiteInfo); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, leftConversion, resultKind, optRightType); } } // SPEC: Otherwise, a and b are incompatible, and a compile-time error occurs. diagnostics.Add(node, useSiteInfo); return GenerateNullCoalescingBadBinaryOpsError(node, leftOperand, rightOperand, Conversion.NoConversion, diagnostics); } private BoundExpression BindNullCoalescingAssignmentOperator(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression leftOperand = BindValue(node.Left, diagnostics, BindValueKind.CompoundAssignment); ReportSuppressionIfNeeded(leftOperand, diagnostics); BoundExpression rightOperand = BindValue(node.Right, diagnostics, BindValueKind.RValue); // If either operand is bad, bail out preventing more cascading errors if (leftOperand.HasAnyErrors || rightOperand.HasAnyErrors) { leftOperand = BindToTypeForErrorRecovery(leftOperand); rightOperand = BindToTypeForErrorRecovery(rightOperand); return new BoundNullCoalescingAssignmentOperator(node, leftOperand, rightOperand, CreateErrorType(), hasErrors: true); } // Given a ??= b, the type of a is A, the type of B is b, and if A is a nullable value type, the underlying // non-nullable value type of A is A0. TypeSymbol leftType = leftOperand.Type; Debug.Assert((object)leftType != null); // If A is a non-nullable value type, a compile-time error occurs if (leftType.IsValueType && !leftType.IsNullableType()) { return GenerateNullCoalescingAssignmentBadBinaryOpsError(node, leftOperand, rightOperand, diagnostics); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // If A0 exists and B is implicitly convertible to A0, then the result type of this expression is A0, except if B is dynamic. // This differs from most assignments such that you cannot directly replace a with (a ??= b). // The exception for dynamic is called out in the spec, it's the same behavior that ?? has with respect to dynamic. if (leftType.IsNullableType()) { var underlyingLeftType = leftType.GetNullableUnderlyingType(); var underlyingRightConversion = Conversions.ClassifyImplicitConversionFromExpression(rightOperand, underlyingLeftType, ref useSiteInfo); if (underlyingRightConversion.Exists && rightOperand.Type?.IsDynamic() != true) { diagnostics.Add(node, useSiteInfo); var convertedRightOperand = CreateConversion(rightOperand, underlyingRightConversion, underlyingLeftType, diagnostics); return new BoundNullCoalescingAssignmentOperator(node, leftOperand, convertedRightOperand, underlyingLeftType); } } // If an implicit conversion exists from B to A, we store that conversion. At runtime, a is first evaluated. If // a is not null, b is not evaluated. If a is null, b is evaluated and converted to type A, and is stored in a. // Reset useSiteDiagnostics because they could have been used populated incorrectly from attempting to bind // as the nullable underlying value type case. useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); var rightConversion = Conversions.ClassifyImplicitConversionFromExpression(rightOperand, leftType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (rightConversion.Exists) { var convertedRightOperand = CreateConversion(rightOperand, rightConversion, leftType, diagnostics); return new BoundNullCoalescingAssignmentOperator(node, leftOperand, convertedRightOperand, leftType); } // a and b are incompatible and a compile-time error occurs return GenerateNullCoalescingAssignmentBadBinaryOpsError(node, leftOperand, rightOperand, diagnostics); } private BoundExpression GenerateNullCoalescingAssignmentBadBinaryOpsError(AssignmentExpressionSyntax node, BoundExpression leftOperand, BoundExpression rightOperand, BindingDiagnosticBag diagnostics) { Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, SyntaxFacts.GetText(node.OperatorToken.Kind()), leftOperand.Display, rightOperand.Display); leftOperand = BindToTypeForErrorRecovery(leftOperand); rightOperand = BindToTypeForErrorRecovery(rightOperand); return new BoundNullCoalescingAssignmentOperator(node, leftOperand, rightOperand, CreateErrorType(), hasErrors: true); } /// <remarks> /// From ExpressionBinder::EnsureQMarkTypesCompatible: /// /// The v2.0 specification states that the types of the second and third operands T and S of a conditional operator /// must be TT and TS such that either (a) TT==TS, or (b), TT->TS or TS->TT but not both. /// /// Unfortunately that is not what we implemented in v2.0. Instead, we implemented /// that either (a) TT=TS or (b) T->TS or S->TT but not both. That is, we looked at the /// convertibility of the expressions, not the types. /// /// /// Changing that to the algorithm in the standard would be a breaking change. /// /// b ? (Func&lt;int&gt;)(delegate(){return 1;}) : (delegate(){return 2;}) /// /// and /// /// b ? 0 : myenum /// /// would suddenly stop working. (The first because o2 has no type, the second because 0 goes to /// any enum but enum doesn't go to int.) /// /// It gets worse. We would like the 3.0 language features which require type inference to use /// a consistent algorithm, and that furthermore, the algorithm be smart about choosing the best /// of a set of types. However, the language committee has decided that this algorithm will NOT /// consume information about the convertibility of expressions. Rather, it will gather up all /// the possible types and then pick the "largest" of them. /// /// To maintain backwards compatibility while still participating in the spirit of consistency, /// we implement an algorithm here which picks the type based on expression convertibility, but /// if there is a conflict, then it chooses the larger type rather than producing a type error. /// This means that b?0:myshort will have type int rather than producing an error (because 0->short, /// myshort->int). /// </remarks> private BoundExpression BindConditionalOperator(ConditionalExpressionSyntax node, BindingDiagnosticBag diagnostics) { var whenTrue = node.WhenTrue.CheckAndUnwrapRefExpression(diagnostics, out var whenTrueRefKind); var whenFalse = node.WhenFalse.CheckAndUnwrapRefExpression(diagnostics, out var whenFalseRefKind); var isRef = whenTrueRefKind == RefKind.Ref && whenFalseRefKind == RefKind.Ref; if (!isRef) { if (whenFalseRefKind == RefKind.Ref) { diagnostics.Add(ErrorCode.ERR_RefConditionalNeedsTwoRefs, whenFalse.GetFirstToken().GetLocation()); } if (whenTrueRefKind == RefKind.Ref) { diagnostics.Add(ErrorCode.ERR_RefConditionalNeedsTwoRefs, whenTrue.GetFirstToken().GetLocation()); } } else { CheckFeatureAvailability(node, MessageID.IDS_FeatureRefConditional, diagnostics); } return isRef ? BindRefConditionalOperator(node, whenTrue, whenFalse, diagnostics) : BindValueConditionalOperator(node, whenTrue, whenFalse, diagnostics); } #nullable enable private BoundExpression BindValueConditionalOperator(ConditionalExpressionSyntax node, ExpressionSyntax whenTrue, ExpressionSyntax whenFalse, BindingDiagnosticBag diagnostics) { BoundExpression condition = BindBooleanExpression(node.Condition, diagnostics); BoundExpression trueExpr = BindValue(whenTrue, diagnostics, BindValueKind.RValue); BoundExpression falseExpr = BindValue(whenFalse, diagnostics, BindValueKind.RValue); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); ConstantValue? constantValue = null; TypeSymbol? bestType = BestTypeInferrer.InferBestTypeForConditionalOperator(trueExpr, falseExpr, this.Conversions, out bool hadMultipleCandidates, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (bestType is null) { ErrorCode noCommonTypeError = hadMultipleCandidates ? ErrorCode.ERR_AmbigQM : ErrorCode.ERR_InvalidQM; constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); return new BoundUnconvertedConditionalOperator(node, condition, trueExpr, falseExpr, constantValue, noCommonTypeError, type: null, hasErrors: constantValue?.IsBad == true); } TypeSymbol type; bool hasErrors; if (bestType.IsErrorType()) { trueExpr = BindToNaturalType(trueExpr, diagnostics, reportNoTargetType: false); falseExpr = BindToNaturalType(falseExpr, diagnostics, reportNoTargetType: false); type = bestType; hasErrors = true; } else { trueExpr = GenerateConversionForAssignment(bestType, trueExpr, diagnostics); falseExpr = GenerateConversionForAssignment(bestType, falseExpr, diagnostics); hasErrors = trueExpr.HasAnyErrors || falseExpr.HasAnyErrors; // If one of the conversions went wrong (e.g. return type of method group being converted // didn't match), then we don't want to use bestType because it's not accurate. type = hasErrors ? CreateErrorType() : bestType; } if (!hasErrors) { constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); hasErrors = constantValue != null && constantValue.IsBad; } return new BoundConditionalOperator(node, isRef: false, condition, trueExpr, falseExpr, constantValue, naturalTypeOpt: type, wasTargetTyped: false, type, hasErrors); } #nullable disable private BoundExpression BindRefConditionalOperator(ConditionalExpressionSyntax node, ExpressionSyntax whenTrue, ExpressionSyntax whenFalse, BindingDiagnosticBag diagnostics) { BoundExpression condition = BindBooleanExpression(node.Condition, diagnostics); BoundExpression trueExpr = BindValue(whenTrue, diagnostics, BindValueKind.RValue | BindValueKind.RefersToLocation); BoundExpression falseExpr = BindValue(whenFalse, diagnostics, BindValueKind.RValue | BindValueKind.RefersToLocation); bool hasErrors = trueExpr.HasErrors | falseExpr.HasErrors; TypeSymbol trueType = trueExpr.Type; TypeSymbol falseType = falseExpr.Type; TypeSymbol type; if (!Conversions.HasIdentityConversion(trueType, falseType)) { if (!hasErrors) diagnostics.Add(ErrorCode.ERR_RefConditionalDifferentTypes, falseExpr.Syntax.Location, trueType); type = CreateErrorType(); hasErrors = true; } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); type = BestTypeInferrer.InferBestTypeForConditionalOperator(trueExpr, falseExpr, this.Conversions, hadMultipleCandidates: out _, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); Debug.Assert(type is { }); Debug.Assert(Conversions.HasIdentityConversion(trueType, type)); Debug.Assert(Conversions.HasIdentityConversion(falseType, type)); } if (!hasErrors) { var currentScope = this.LocalScopeDepth; // val-escape must agree on both branches. uint whenTrueEscape = GetValEscape(trueExpr, currentScope); uint whenFalseEscape = GetValEscape(falseExpr, currentScope); if (whenTrueEscape != whenFalseEscape) { // ask the one with narrower escape, for the wider - hopefully the errors will make the violation easier to fix. if (whenTrueEscape < whenFalseEscape) CheckValEscape(falseExpr.Syntax, falseExpr, currentScope, whenTrueEscape, checkingReceiver: false, diagnostics: diagnostics); else CheckValEscape(trueExpr.Syntax, trueExpr, currentScope, whenFalseEscape, checkingReceiver: false, diagnostics: diagnostics); diagnostics.Add(ErrorCode.ERR_MismatchedRefEscapeInTernary, node.Location); hasErrors = true; } } trueExpr = BindToNaturalType(trueExpr, diagnostics, reportNoTargetType: false); falseExpr = BindToNaturalType(falseExpr, diagnostics, reportNoTargetType: false); return new BoundConditionalOperator(node, isRef: true, condition, trueExpr, falseExpr, constantValueOpt: null, type, wasTargetTyped: false, type, hasErrors); } /// <summary> /// Constant folding for conditional (aka ternary) operators. /// </summary> private static ConstantValue FoldConditionalOperator(BoundExpression condition, BoundExpression trueExpr, BoundExpression falseExpr) { ConstantValue trueValue = trueExpr.ConstantValue; if (trueValue == null || trueValue.IsBad) { return trueValue; } ConstantValue falseValue = falseExpr.ConstantValue; if (falseValue == null || falseValue.IsBad) { return falseValue; } ConstantValue conditionValue = condition.ConstantValue; if (conditionValue == null || conditionValue.IsBad) { return conditionValue; } else if (conditionValue == ConstantValue.True) { return trueValue; } else if (conditionValue == ConstantValue.False) { return falseValue; } else { return ConstantValue.Bad; } } private static void CheckNativeIntegerFeatureAvailability(BinaryOperatorKind operatorKind, SyntaxNode syntax, BindingDiagnosticBag diagnostics) { switch (operatorKind & BinaryOperatorKind.TypeMask) { case BinaryOperatorKind.NInt: case BinaryOperatorKind.NUInt: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureNativeInt, diagnostics); break; } } private static void CheckNativeIntegerFeatureAvailability(UnaryOperatorKind operatorKind, SyntaxNode syntax, BindingDiagnosticBag diagnostics) { switch (operatorKind & UnaryOperatorKind.TypeMask) { case UnaryOperatorKind.NInt: case UnaryOperatorKind.NUInt: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureNativeInt, diagnostics); break; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { node.Left.CheckDeconstructionCompatibleArgument(diagnostics); BoundExpression left = BindValue(node.Left, diagnostics, GetBinaryAssignmentKind(node.Kind())); ReportSuppressionIfNeeded(left, diagnostics); BoundExpression right = BindValue(node.Right, diagnostics, BindValueKind.RValue); BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind()); // If either operand is bad, don't try to do binary operator overload resolution; that will just // make cascading errors. if (left.Kind == BoundKind.EventAccess) { BinaryOperatorKind kindOperator = kind.Operator(); switch (kindOperator) { case BinaryOperatorKind.Addition: case BinaryOperatorKind.Subtraction: return BindEventAssignment(node, (BoundEventAccess)left, right, kindOperator, diagnostics); // fall-through for other operators, if RHS is dynamic we produce dynamic operation, otherwise we'll report an error ... } } if (left.HasAnyErrors || right.HasAnyErrors) { // NOTE: no overload resolution candidates. left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (left.HasDynamicType() || right.HasDynamicType()) { if (IsLegalDynamicOperand(right) && IsLegalDynamicOperand(left)) { left = BindToNaturalType(left, diagnostics); right = BindToNaturalType(right, diagnostics); var finalDynamicConversion = this.Compilation.Conversions.ClassifyConversionFromExpression(right, left.Type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); return new BoundCompoundAssignmentOperator( node, new BinaryOperatorSignature( kind.WithType(BinaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), left.Type, right.Type, Compilation.DynamicType), left, right, Conversion.NoConversion, finalDynamicConversion, LookupResultKind.Viable, left.Type, hasErrors: false); } else { Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, node.OperatorToken.Text, left.Display, right.Display); // error: operator can't be applied on dynamic and a type that is not convertible to dynamic: left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); } } if (left.Kind == BoundKind.EventAccess && !CheckEventValueKind((BoundEventAccess)left, BindValueKind.Assignable, diagnostics)) { // If we're in a place where the event can be assigned, then continue so that we give errors // about the types and operator not lining up. Otherwise, just report that the event can't // be used here. // NOTE: no overload resolution candidates. left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.NotAVariable, CreateErrorType(), hasErrors: true); } // A compound operator, say, x |= y, is bound as x = (X)( ((T)x) | ((T)y) ). We must determine // the binary operator kind, the type conversions from each side to the types expected by // the operator, and the type conversion from the return type of the operand to the left hand side. // // We can get away with binding the right-hand-side of the operand into its converted form early. // This is convenient because first, it is never rewritten into an access to a temporary before // the conversion, and second, because that is more convenient for the "d += lambda" case. // We want to have the converted (bound) lambda in the bound tree, not the unconverted unbound lambda. LookupResultKind resultKind; ImmutableArray<MethodSymbol> originalUserDefinedOperators; BinaryOperatorAnalysisResult best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); if (!best.HasValue) { ReportAssignmentOperatorError(node, diagnostics, left, right, resultKind); left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundCompoundAssignmentOperator(node, BinaryOperatorSignature.Error, left, right, Conversion.NoConversion, Conversion.NoConversion, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); } // The rules in the spec for determining additional errors are bit confusing. In particular // this line is misleading: // // "for predefined operators ... x op= y is permitted if both x op y and x = y are permitted" // // That's not accurate in many cases. For example, "x += 1" is permitted if x is string or // any enum type, but x = 1 is not legal for strings or enums. // // The correct rules are spelled out in the spec: // // Spec §7.17.2: // An operation of the form x op= y is processed by applying binary operator overload // resolution (§7.3.4) as if the operation was written x op y. // Let R be the return type of the selected operator, and T the type of x. Then, // // * If an implicit conversion from an expression of type R to the type T exists, // the operation is evaluated as x = (T)(x op y), except that x is evaluated only once. // [no cast is inserted, unless the conversion is implicit dynamic] // * Otherwise, if // (1) the selected operator is a predefined operator, // (2) if R is explicitly convertible to T, and // (3.1) if y is implicitly convertible to T or // (3.2) the operator is a shift operator... [then cast the result to T] // * Otherwise ... a binding-time error occurs. // So let's tease that out. There are two possible errors: the conversion from the // operator result type to the left hand type could be bad, and the conversion // from the right hand side to the left hand type could be bad. // // We report the first error under the following circumstances: // // * The final conversion is bad, or // * The final conversion is explicit and the selected operator is not predefined // // We report the second error under the following circumstances: // // * The final conversion is explicit, and // * The selected operator is predefined, and // * the selected operator is not a shift, and // * the right-to-left conversion is not implicit bool hasError = false; BinaryOperatorSignature bestSignature = best.Signature; CheckNativeIntegerFeatureAvailability(bestSignature.Kind, node, diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, bestSignature.Method, bestSignature.ConstrainedToTypeOpt, diagnostics); if (CheckOverflowAtRuntime) { bestSignature = new BinaryOperatorSignature( bestSignature.Kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), bestSignature.LeftType, bestSignature.RightType, bestSignature.ReturnType, bestSignature.Method, bestSignature.ConstrainedToTypeOpt); } BoundExpression rightConverted = CreateConversion(right, best.RightConversion, bestSignature.RightType, diagnostics); var leftType = left.Type; Conversion finalConversion = Conversions.ClassifyConversionFromExpressionType(bestSignature.ReturnType, leftType, ref useSiteInfo); bool isPredefinedOperator = !bestSignature.Kind.IsUserDefined(); if (!finalConversion.IsValid || finalConversion.IsExplicit && !isPredefinedOperator) { hasError = true; GenerateImplicitConversionError(diagnostics, this.Compilation, node, finalConversion, bestSignature.ReturnType, leftType); } else { ReportDiagnosticsIfObsolete(diagnostics, finalConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, finalConversion, diagnostics); } if (finalConversion.IsExplicit && isPredefinedOperator && !kind.IsShift()) { Conversion rightToLeftConversion = this.Conversions.ClassifyConversionFromExpression(right, leftType, ref useSiteInfo); if (!rightToLeftConversion.IsImplicit || !rightToLeftConversion.IsValid) { hasError = true; GenerateImplicitConversionError(diagnostics, node, rightToLeftConversion, right, leftType); } } diagnostics.Add(node, useSiteInfo); if (!hasError && leftType.IsVoidPointer()) { Error(diagnostics, ErrorCode.ERR_VoidError, node); hasError = true; } // Any events that weren't handled above (by BindEventAssignment) are bad - we just followed this // code path for the diagnostics. Make sure we don't report success. Debug.Assert(left.Kind != BoundKind.EventAccess || hasError); Conversion leftConversion = best.LeftConversion; ReportDiagnosticsIfObsolete(diagnostics, leftConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, leftConversion, diagnostics); return new BoundCompoundAssignmentOperator(node, bestSignature, left, rightConverted, leftConversion, finalConversion, resultKind, originalUserDefinedOperators, leftType, hasError); } /// <summary> /// For "receiver.event += expr", produce "receiver.add_event(expr)". /// For "receiver.event -= expr", produce "receiver.remove_event(expr)". /// </summary> /// <remarks> /// Performs some validation of the accessor that couldn't be done in CheckEventValueKind, because /// the specific accessor wasn't known. /// </remarks> private BoundExpression BindEventAssignment(AssignmentExpressionSyntax node, BoundEventAccess left, BoundExpression right, BinaryOperatorKind opKind, BindingDiagnosticBag diagnostics) { Debug.Assert(opKind == BinaryOperatorKind.Addition || opKind == BinaryOperatorKind.Subtraction); bool hasErrors = false; EventSymbol eventSymbol = left.EventSymbol; BoundExpression receiverOpt = left.ReceiverOpt; TypeSymbol delegateType = left.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion argumentConversion = this.Conversions.ClassifyConversionFromExpression(right, delegateType, ref useSiteInfo); if (!argumentConversion.IsImplicit || !argumentConversion.IsValid) // NOTE: dev10 appears to allow user-defined conversions here. { hasErrors = true; if (delegateType.IsDelegateType()) // Otherwise, suppress cascading. { GenerateImplicitConversionError(diagnostics, node, argumentConversion, right, delegateType); } } BoundExpression argument = CreateConversion(right, argumentConversion, delegateType, diagnostics); bool isAddition = opKind == BinaryOperatorKind.Addition; MethodSymbol method = isAddition ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; TypeSymbol type; if ((object)method == null) { type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); //we know the return type would have been void // There will be a diagnostic on the declaration if it is from source. if (!eventSymbol.OriginalDefinition.IsFromCompilation(this.Compilation)) { // CONSIDER: better error code? ERR_EventNeedsBothAccessors? Error(diagnostics, ErrorCode.ERR_MissingPredefinedMember, node, delegateType, SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAddition)); } } else { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, method, diagnostics); if (!this.IsAccessible(method, ref useSiteInfo, this.GetAccessThroughType(receiverOpt))) { // CONSIDER: depending on the accessibility (e.g. if it's private), dev10 might just report the whole event bogus. Error(diagnostics, ErrorCode.ERR_BadAccess, node, method); hasErrors = true; } else if (IsBadBaseAccess(node, receiverOpt, method, diagnostics, eventSymbol)) { hasErrors = true; } else { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, method, diagnostics); } if (eventSymbol.IsWindowsRuntimeEvent) { // Return type is actually void because this call will be later encapsulated in a call // to WindowsRuntimeMarshal.AddEventHandler or RemoveEventHandler, which has the return // type of void. type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); } else { type = method.ReturnType; } } diagnostics.Add(node, useSiteInfo); return new BoundEventAssignmentOperator( syntax: node, @event: eventSymbol, isAddition: isAddition, isDynamic: right.HasDynamicType(), receiverOpt: receiverOpt, argument: argument, type: type, hasErrors: hasErrors); } private static bool IsLegalDynamicOperand(BoundExpression operand) { Debug.Assert(operand != null); TypeSymbol type = operand.Type; // Literal null is a legal operand to a dynamic operation. The other typeless expressions -- // method groups, lambdas, anonymous methods -- are not. // If the operand is of a class, interface, delegate, array, struct, enum, nullable // or type param types, it's legal to use in a dynamic expression. In short, the type // must be one that is convertible to object. if ((object)type == null) { return operand.IsLiteralNull(); } // Pointer types and very special types are not convertible to object. return !type.IsPointerOrFunctionPointer() && !type.IsRestrictedType() && !type.IsVoidType(); } private BoundExpression BindDynamicBinaryOperator( BinaryExpressionSyntax node, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) { // This method binds binary * / % + - << >> < > <= >= == != & ! ^ && || operators where one or both // of the operands are dynamic. Debug.Assert((object)left.Type != null && left.Type.IsDynamic() || (object)right.Type != null && right.Type.IsDynamic()); bool hasError = false; bool leftValidOperand = IsLegalDynamicOperand(left); bool rightValidOperand = IsLegalDynamicOperand(right); if (!leftValidOperand || !rightValidOperand) { // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, node.OperatorToken.Text, left.Display, right.Display); hasError = true; } MethodSymbol userDefinedOperator = null; if (kind.IsLogical() && leftValidOperand) { // We need to make sure left is either implicitly convertible to Boolean or has user defined truth operator. // left && right is lowered to {op_False|op_Implicit}(left) ? left : And(left, right) // left || right is lowered to {op_True|!op_Implicit}(left) ? left : Or(left, right) CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (!IsValidDynamicCondition(left, isNegative: kind == BinaryOperatorKind.LogicalAnd, useSiteInfo: ref useSiteInfo, userDefinedOperator: out userDefinedOperator)) { // Dev11 reports ERR_MustHaveOpTF. The error was shared between this case and user-defined binary Boolean operators. // We report two distinct more specific error messages. Error(diagnostics, ErrorCode.ERR_InvalidDynamicCondition, node.Left, left.Type, kind == BinaryOperatorKind.LogicalAnd ? "false" : "true"); hasError = true; } else { Debug.Assert(left.Type is not TypeParameterSymbol); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, userDefinedOperator, constrainedToTypeOpt: null, diagnostics); } diagnostics.Add(node, useSiteInfo); } return new BoundBinaryOperator( syntax: node, operatorKind: (hasError ? kind : kind.WithType(BinaryOperatorKind.Dynamic)).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), left: BindToNaturalType(left, diagnostics), right: BindToNaturalType(right, diagnostics), constantValueOpt: ConstantValue.NotAvailable, methodOpt: userDefinedOperator, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, type: Compilation.DynamicType, hasErrors: hasError); } protected static bool IsSimpleBinaryOperator(SyntaxKind kind) { // We deliberately exclude &&, ||, ??, etc. switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: return true; } return false; } private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { // The simple binary operators are left-associative, and expressions of the form // a + b + c + d .... are relatively common in machine-generated code. The parser can handle // creating a deep-on-the-left syntax tree no problem, and then we promptly blow the stack during // semantic analysis. Here we build an explicit stack to handle the left-hand recursion. Debug.Assert(IsSimpleBinaryOperator(node.Kind())); var syntaxNodes = ArrayBuilder<BinaryExpressionSyntax>.GetInstance(); ExpressionSyntax current = node; while (IsSimpleBinaryOperator(current.Kind())) { var binOp = (BinaryExpressionSyntax)current; syntaxNodes.Push(binOp); current = binOp.Left; } BoundExpression result = BindExpression(current, diagnostics); if (node.IsKind(SyntaxKind.SubtractExpression) && current.IsKind(SyntaxKind.ParenthesizedExpression)) { if (result.Kind == BoundKind.TypeExpression && !((ParenthesizedExpressionSyntax)current).Expression.IsKind(SyntaxKind.ParenthesizedExpression)) { Error(diagnostics, ErrorCode.ERR_PossibleBadNegCast, node); } else if (result.Kind == BoundKind.BadExpression) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)current; if (parenthesizedExpression.Expression.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)parenthesizedExpression.Expression).Identifier.ValueText == "dynamic") { Error(diagnostics, ErrorCode.ERR_PossibleBadNegCast, node); } } } while (syntaxNodes.Count > 0) { BinaryExpressionSyntax syntaxNode = syntaxNodes.Pop(); BindValueKind bindValueKind = GetBinaryAssignmentKind(syntaxNode.Kind()); BoundExpression left = CheckValue(result, bindValueKind, diagnostics); BoundExpression right = BindValue(syntaxNode.Right, diagnostics, BindValueKind.RValue); BoundExpression boundOp = BindSimpleBinaryOperator(syntaxNode, diagnostics, left, right, leaveUnconvertedIfInterpolatedString: true); result = boundOp; } syntaxNodes.Free(); return result; } private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, bool leaveUnconvertedIfInterpolatedString) { BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind()); // If either operand is bad, don't try to do binary operator overload resolution; that would just // make cascading errors. if (left.HasAnyErrors || right.HasAnyErrors) { // NOTE: no user-defined conversion candidates left = BindToTypeForErrorRecovery(left); right = BindToTypeForErrorRecovery(right); return new BoundBinaryOperator(node, kind, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Empty, left, right, GetBinaryOperatorErrorType(kind, diagnostics, node), true); } TypeSymbol leftType = left.Type; TypeSymbol rightType = right.Type; if ((object)leftType != null && leftType.IsDynamic() || (object)rightType != null && rightType.IsDynamic()) { return BindDynamicBinaryOperator(node, kind, left, right, diagnostics); } // SPEC OMISSION: The C# 2.0 spec had a line in it that noted that the expressions "null == null" // SPEC OMISSION: and "null != null" were to be automatically treated as the appropriate constant; // SPEC OMISSION: overload resolution was to be skipped. That's because a strict reading // SPEC OMISSION: of the overload resolution spec shows that overload resolution would give an // SPEC OMISSION: ambiguity error for this case; the expression is ambiguous between the int?, // SPEC OMISSION: bool? and string versions of equality. This line was accidentally edited // SPEC OMISSION: out of the C# 3 specification; we should re-insert it. bool leftNull = left.IsLiteralNull(); bool rightNull = right.IsLiteralNull(); bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual; if (isEquality && leftNull && rightNull) { return new BoundLiteral(node, ConstantValue.Create(kind == BinaryOperatorKind.Equal), GetSpecialType(SpecialType.System_Boolean, diagnostics, node)); } if (IsTupleBinaryOperation(left, right) && (kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual)) { CheckFeatureAvailability(node, MessageID.IDS_FeatureTupleEquality, diagnostics); return BindTupleBinaryOperator(node, kind, left, right, diagnostics); } if (leaveUnconvertedIfInterpolatedString && kind == BinaryOperatorKind.Addition && left is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true } && right is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }) { Debug.Assert(right.Type.SpecialType == SpecialType.System_String); var stringConstant = FoldBinaryOperator(node, BinaryOperatorKind.StringConcatenation, left, right, right.Type, diagnostics); return new BoundBinaryOperator(node, BinaryOperatorKind.StringConcatenation, BoundBinaryOperator.UncommonData.UnconvertedInterpolatedStringAddition(stringConstant), LookupResultKind.Empty, left, right, right.Type); } // SPEC: For an operation of one of the forms x == null, null == x, x != null, null != x, // SPEC: where x is an expression of nullable type, if operator overload resolution // SPEC: fails to find an applicable operator, the result is instead computed from // SPEC: the HasValue property of x. // Note that the spec says "fails to find an applicable operator", not "fails to // find a unique best applicable operator." For example: // struct X { // public static bool operator ==(X? x, double? y) {...} // public static bool operator ==(X? x, decimal? y) {...} // // The comparison "x == null" should produce an ambiguity error rather // that being bound as !x.HasValue. // LookupResultKind resultKind; ImmutableArray<MethodSymbol> originalUserDefinedOperators; BinaryOperatorSignature signature; BinaryOperatorAnalysisResult best; bool foundOperator = BindSimpleBinaryOperatorParts(node, diagnostics, left, right, kind, out resultKind, out originalUserDefinedOperators, out signature, out best); BinaryOperatorKind resultOperatorKind = signature.Kind; bool hasErrors = false; if (!foundOperator) { ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind); resultOperatorKind &= ~BinaryOperatorKind.TypeMask; hasErrors = true; } switch (node.Kind()) { case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: // Function pointer comparisons are defined on `void*` with implicit conversions to `void*` on both sides. So if this is a // pointer comparison operation, and the underlying types of the left and right are both function pointers, then we need to // warn about them because of JIT recompilation. If either side is explicitly cast to void*, that side's type will be void*, // not delegate*, and we won't warn. if ((resultOperatorKind & BinaryOperatorKind.Pointer) == BinaryOperatorKind.Pointer && leftType?.TypeKind == TypeKind.FunctionPointer && rightType?.TypeKind == TypeKind.FunctionPointer) { // Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct. Error(diagnostics, ErrorCode.WRN_DoNotCompareFunctionPointers, node.OperatorToken); } break; default: if (leftType.IsVoidPointer() || rightType.IsVoidPointer()) { // CONSIDER: dev10 cascades this, but roslyn doesn't have to. Error(diagnostics, ErrorCode.ERR_VoidError, node); hasErrors = true; } break; } CheckNativeIntegerFeatureAvailability(resultOperatorKind, node, diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); TypeSymbol resultType = signature.ReturnType; BoundExpression resultLeft = left; BoundExpression resultRight = right; ConstantValue resultConstant = null; if (foundOperator && (resultOperatorKind.OperandTypes() != BinaryOperatorKind.NullableNull)) { Debug.Assert((object)signature.LeftType != null); Debug.Assert((object)signature.RightType != null); resultLeft = CreateConversion(left, best.LeftConversion, signature.LeftType, diagnostics); resultRight = CreateConversion(right, best.RightConversion, signature.RightType, diagnostics); resultConstant = FoldBinaryOperator(node, resultOperatorKind, resultLeft, resultRight, resultType, diagnostics); } else { // If we found an operator, we'll have given the `default` literal a type. // Otherwise, we'll have reported the problem in ReportBinaryOperatorError. resultLeft = BindToNaturalType(resultLeft, diagnostics, reportNoTargetType: false); resultRight = BindToNaturalType(resultRight, diagnostics, reportNoTargetType: false); } hasErrors = hasErrors || resultConstant != null && resultConstant.IsBad; return new BoundBinaryOperator( node, resultOperatorKind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), resultLeft, resultRight, resultConstant, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, resultType, hasErrors); } private bool BindSimpleBinaryOperatorParts(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, BinaryOperatorKind kind, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators, out BinaryOperatorSignature resultSignature, out BinaryOperatorAnalysisResult best) { bool foundOperator; best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); // However, as an implementation detail, we never "fail to find an applicable // operator" during overload resolution if we have x == null, x == default, etc. We always // find at least the reference conversion object == object; the overload resolution // code does not reject that. Therefore what we should do is only bind // "x == null" as a nullable-to-null comparison if overload resolution chooses // the reference conversion. if (!best.HasValue) { resultSignature = new BinaryOperatorSignature(kind, leftType: null, rightType: null, CreateErrorType()); foundOperator = false; } else { var signature = best.Signature; bool isObjectEquality = signature.Kind == BinaryOperatorKind.ObjectEqual || signature.Kind == BinaryOperatorKind.ObjectNotEqual; bool leftNull = left.IsLiteralNull(); bool rightNull = right.IsLiteralNull(); TypeSymbol leftType = left.Type; TypeSymbol rightType = right.Type; bool isNullableEquality = (object)signature.Method == null && (signature.Kind.Operator() == BinaryOperatorKind.Equal || signature.Kind.Operator() == BinaryOperatorKind.NotEqual) && (leftNull && (object)rightType != null && rightType.IsNullableType() || rightNull && (object)leftType != null && leftType.IsNullableType()); if (isNullableEquality) { resultSignature = new BinaryOperatorSignature(kind | BinaryOperatorKind.NullableNull, leftType: null, rightType: null, GetSpecialType(SpecialType.System_Boolean, diagnostics, node)); foundOperator = true; } else { resultSignature = signature; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool leftDefault = left.IsLiteralDefault(); bool rightDefault = right.IsLiteralDefault(); foundOperator = !isObjectEquality || BuiltInOperators.IsValidObjectEquality(Conversions, leftType, leftNull, leftDefault, rightType, rightNull, rightDefault, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); } } return foundOperator; } #nullable enable private BoundExpression RebindSimpleBinaryOperatorAsConverted(BoundBinaryOperator unconvertedBinaryOperator, BindingDiagnosticBag diagnostics) { if (TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(unconvertedBinaryOperator, diagnostics, out var convertedBinaryOperator)) { return convertedBinaryOperator; } var result = doRebind(diagnostics, unconvertedBinaryOperator); return result; BoundExpression doRebind(BindingDiagnosticBag diagnostics, BoundBinaryOperator? current) { var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); while (current != null) { Debug.Assert(current.IsUnconvertedInterpolatedStringAddition); stack.Push(current); current = current.Left as BoundBinaryOperator; } Debug.Assert(stack.Count > 0 && stack.Peek().Left is BoundUnconvertedInterpolatedString); BoundExpression? left = null; while (stack.TryPop(out current)) { var right = current.Right switch { BoundUnconvertedInterpolatedString s => s, BoundBinaryOperator b => doRebind(diagnostics, b), _ => throw ExceptionUtilities.UnexpectedValue(current.Right.Kind) }; left = BindSimpleBinaryOperator((BinaryExpressionSyntax)current.Syntax, diagnostics, left ?? current.Left, right, leaveUnconvertedIfInterpolatedString: false); } Debug.Assert(left != null); Debug.Assert(stack.Count == 0); stack.Free(); return left; } } #nullable disable private static void ReportUnaryOperatorError(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, string operatorName, BoundExpression operand, LookupResultKind resultKind) { if (operand.IsLiteralDefault()) { // We'll have reported an error for not being able to target-type `default` so we can avoid a cascading diagnostic return; } ErrorCode errorCode = resultKind == LookupResultKind.Ambiguous ? ErrorCode.ERR_AmbigUnaryOp : // Operator '{0}' is ambiguous on an operand of type '{1}' ErrorCode.ERR_BadUnaryOp; // Operator '{0}' cannot be applied to operand of type '{1}' Error(diagnostics, errorCode, node, operatorName, operand.Display); } private void ReportAssignmentOperatorError(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, LookupResultKind resultKind) { if (((SyntaxKind)node.OperatorToken.RawKind == SyntaxKind.PlusEqualsToken || (SyntaxKind)node.OperatorToken.RawKind == SyntaxKind.MinusEqualsToken) && (object)left.Type != null && left.Type.TypeKind == TypeKind.Delegate) { // Special diagnostic for delegate += and -= about wrong right-hand-side var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = this.Conversions.ClassifyConversionFromExpression(right, left.Type, ref discardedUseSiteInfo); Debug.Assert(!conversion.IsImplicit); GenerateImplicitConversionError(diagnostics, right.Syntax, conversion, right, left.Type); // discard use-site diagnostics } else { ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind); } } private static void ReportBinaryOperatorError(ExpressionSyntax node, BindingDiagnosticBag diagnostics, SyntaxToken operatorToken, BoundExpression left, BoundExpression right, LookupResultKind resultKind) { bool isEquality = operatorToken.Kind() == SyntaxKind.EqualsEqualsToken || operatorToken.Kind() == SyntaxKind.ExclamationEqualsToken; switch (left.Kind, right.Kind) { case (BoundKind.DefaultLiteral, _) when !isEquality: case (_, BoundKind.DefaultLiteral) when !isEquality: // other than == and !=, binary operators are disallowed on `default` literal Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, "default"); return; case (BoundKind.DefaultLiteral, BoundKind.DefaultLiteral): Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnDefault, node, operatorToken.Text, left.Display, right.Display); return; case (BoundKind.DefaultLiteral, _) when right.Type is TypeParameterSymbol: Debug.Assert(!right.Type.IsReferenceType); Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault, node, operatorToken.Text, right.Type); return; case (_, BoundKind.DefaultLiteral) when left.Type is TypeParameterSymbol: Debug.Assert(!left.Type.IsReferenceType); Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault, node, operatorToken.Text, left.Type); return; case (BoundKind.UnconvertedObjectCreationExpression, _): Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, left.Display); return; case (_, BoundKind.UnconvertedObjectCreationExpression): Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorToken.Text, right.Display); return; } ErrorCode errorCode = resultKind == LookupResultKind.Ambiguous ? ErrorCode.ERR_AmbigBinaryOps : // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' ErrorCode.ERR_BadBinaryOps; // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' Error(diagnostics, errorCode, node, operatorToken.Text, left.Display, right.Display); } private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.LogicalOrExpression || node.Kind() == SyntaxKind.LogicalAndExpression); // Do not blow the stack due to a deep recursion on the left. BinaryExpressionSyntax binary = node; ExpressionSyntax child; while (true) { child = binary.Left; var childAsBinary = child as BinaryExpressionSyntax; if (childAsBinary == null || (childAsBinary.Kind() != SyntaxKind.LogicalOrExpression && childAsBinary.Kind() != SyntaxKind.LogicalAndExpression)) { break; } binary = childAsBinary; } BoundExpression left = BindRValueWithoutTargetType(child, diagnostics); do { binary = (BinaryExpressionSyntax)child.Parent; BoundExpression right = BindRValueWithoutTargetType(binary.Right, diagnostics); left = BindConditionalLogicalOperator(binary, left, right, diagnostics); child = binary; } while ((object)child != node); return left; } private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax node, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) { BinaryOperatorKind kind = SyntaxKindToBinaryOperatorKind(node.Kind()); Debug.Assert(kind == BinaryOperatorKind.LogicalAnd || kind == BinaryOperatorKind.LogicalOr); // Let's take an easy out here. The vast majority of the time the operands will // both be bool. This is the only situation in which the expression can be a // constant expression, so do the folding now if we can. if ((object)left.Type != null && left.Type.SpecialType == SpecialType.System_Boolean && (object)right.Type != null && right.Type.SpecialType == SpecialType.System_Boolean) { var constantValue = FoldBinaryOperator(node, kind | BinaryOperatorKind.Bool, left, right, left.Type, diagnostics); // NOTE: no candidate user-defined operators. return new BoundBinaryOperator(node, kind | BinaryOperatorKind.Bool, constantValue, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, left, right, type: left.Type, hasErrors: constantValue != null && constantValue.IsBad); } // If either operand is bad, don't try to do binary operator overload resolution; that will just // make cascading errors. if (left.HasAnyErrors || right.HasAnyErrors) { // NOTE: no candidate user-defined operators. return new BoundBinaryOperator(node, kind, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Empty, left, right, type: GetBinaryOperatorErrorType(kind, diagnostics, node), hasErrors: true); } if (left.HasDynamicType() || right.HasDynamicType()) { left = BindToNaturalType(left, diagnostics); right = BindToNaturalType(right, diagnostics); return BindDynamicBinaryOperator(node, kind, left, right, diagnostics); } LookupResultKind lookupResult; ImmutableArray<MethodSymbol> originalUserDefinedOperators; var best = this.BinaryOperatorOverloadResolution(kind, left, right, node, diagnostics, out lookupResult, out originalUserDefinedOperators); // SPEC: If overload resolution fails to find a single best operator, or if overload // SPEC: resolution selects one of the predefined integer logical operators, a binding- // SPEC: time error occurs. // // SPEC OMISSION: We should probably clarify that the enum logical operators count as // SPEC OMISSION: integer logical operators. Basically the rule here should actually be: // SPEC OMISSION: if overload resolution selects something other than a user-defined // SPEC OMISSION: operator or the built in not-lifted operator on bool, an error occurs. // if (!best.HasValue) { ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, lookupResult); } else { // There are two non-error possibilities. Either both operands are implicitly convertible to // bool, or we've got a valid user-defined operator. BinaryOperatorSignature signature = best.Signature; bool bothBool = signature.LeftType.SpecialType == SpecialType.System_Boolean && signature.RightType.SpecialType == SpecialType.System_Boolean; MethodSymbol trueOperator = null, falseOperator = null; if (!bothBool && !signature.Kind.IsUserDefined()) { ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, lookupResult); } else if (bothBool || IsValidUserDefinedConditionalLogicalOperator(node, signature, diagnostics, out trueOperator, out falseOperator)) { var resultLeft = CreateConversion(left, best.LeftConversion, signature.LeftType, diagnostics); var resultRight = CreateConversion(right, best.RightConversion, signature.RightType, diagnostics); var resultKind = kind | signature.Kind.OperandTypes(); if (signature.Kind.IsLifted()) { resultKind |= BinaryOperatorKind.Lifted; } if (resultKind.IsUserDefined()) { Debug.Assert(trueOperator != null && falseOperator != null); _ = CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics) && CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, kind == BinaryOperatorKind.LogicalAnd ? falseOperator : trueOperator, signature.ConstrainedToTypeOpt, diagnostics); return new BoundUserDefinedConditionalLogicalOperator( node, resultKind, resultLeft, resultRight, signature.Method, trueOperator, falseOperator, signature.ConstrainedToTypeOpt, lookupResult, originalUserDefinedOperators, signature.ReturnType); } else { Debug.Assert(bothBool); Debug.Assert(!(signature.Method?.ContainingType?.IsInterface ?? false)); return new BoundBinaryOperator( node, resultKind, resultLeft, resultRight, ConstantValue.NotAvailable, signature.Method, signature.ConstrainedToTypeOpt, lookupResult, originalUserDefinedOperators, signature.ReturnType); } } } // We've already reported the error. return new BoundBinaryOperator(node, kind, left, right, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, lookupResult, originalUserDefinedOperators, CreateErrorType(), true); } private bool IsValidDynamicCondition(BoundExpression left, bool isNegative, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out MethodSymbol userDefinedOperator) { userDefinedOperator = null; var type = left.Type; if ((object)type == null) { return false; } if (type.IsDynamic()) { return true; } var implicitConversion = Conversions.ClassifyImplicitConversionFromExpression(left, Compilation.GetSpecialType(SpecialType.System_Boolean), ref useSiteInfo); if (implicitConversion.Exists) { return true; } if (type.Kind != SymbolKind.NamedType) { return false; } var namedType = type as NamedTypeSymbol; return HasApplicableBooleanOperator(namedType, isNegative ? WellKnownMemberNames.FalseOperatorName : WellKnownMemberNames.TrueOperatorName, type, ref useSiteInfo, out userDefinedOperator); } private bool IsValidUserDefinedConditionalLogicalOperator( CSharpSyntaxNode syntax, BinaryOperatorSignature signature, BindingDiagnosticBag diagnostics, out MethodSymbol trueOperator, out MethodSymbol falseOperator) { Debug.Assert(signature.Kind.OperandTypes() == BinaryOperatorKind.UserDefined); // SPEC: When the operands of && or || are of types that declare an applicable // SPEC: user-defined operator & or |, both of the following must be true, where // SPEC: T is the type in which the selected operator is defined: // SPEC VIOLATION: // // The native compiler violates the specification, the native compiler allows: // // public static D? operator &(D? d1, D? d2) { ... } // public static bool operator true(D? d) { ... } // public static bool operator false(D? d) { ... } // // to be used as D? && D? or D? || D?. But if you do this: // // public static D operator &(D d1, D d2) { ... } // public static bool operator true(D? d) { ... } // public static bool operator false(D? d) { ... } // // And use the *lifted* form of the operator, this is disallowed. // // public static D? operator &(D? d1, D d2) { ... } // public static bool operator true(D? d) { ... } // public static bool operator false(D? d) { ... } // // Is not allowed because "the return type must be the same as the type of both operands" // which is not at all what the spec says. // // We ought not to break backwards compatibility with the native compiler. The spec // is plausibly in error; it is possible that this section of the specification was // never updated when nullable types and lifted operators were added to the language. // And it seems like the native compiler's behavior of allowing a nullable // version but not a lifted version is a bug that should be fixed. // // Therefore we will do the following in Roslyn: // // * The return and parameter types of the chosen operator, whether lifted or unlifted, // must be the same. // * The return and parameter types must be either the enclosing type, or its corresponding // nullable type. // * There must be an operator true/operator false that takes the left hand type of the operator. // Only classes and structs contain user-defined operators, so we know it is a named type symbol. NamedTypeSymbol t = (NamedTypeSymbol)signature.Method.ContainingType; // SPEC: The return type and the type of each parameter of the selected operator // SPEC: must be T. // As mentioned above, we relax this restriction. The types must all be the same. bool typesAreSame = TypeSymbol.Equals(signature.LeftType, signature.RightType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(signature.LeftType, signature.ReturnType, TypeCompareKind.ConsiderEverything2); MethodSymbol definition; bool typeMatchesContainer = TypeSymbol.Equals(signature.ReturnType.StrippedType(), t, TypeCompareKind.ConsiderEverything2) || (t.IsInterface && signature.Method.IsAbstract && SourceUserDefinedOperatorSymbol.IsSelfConstrainedTypeParameter((definition = signature.Method.OriginalDefinition).ReturnType.StrippedType(), definition.ContainingType)); if (!typesAreSame || !typeMatchesContainer) { // CS0217: In order to be applicable as a short circuit operator a user-defined logical // operator ('{0}') must have the same return type and parameter types Error(diagnostics, ErrorCode.ERR_BadBoolOp, syntax, signature.Method); trueOperator = null; falseOperator = null; return false; } // SPEC: T must contain declarations of operator true and operator false. // As mentioned above, we need more than just op true and op false existing; we need // to know that the first operand can be passed to it. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (!HasApplicableBooleanOperator(t, WellKnownMemberNames.TrueOperatorName, signature.LeftType, ref useSiteInfo, out trueOperator) || !HasApplicableBooleanOperator(t, WellKnownMemberNames.FalseOperatorName, signature.LeftType, ref useSiteInfo, out falseOperator)) { // I have changed the wording of this error message. The original wording was: // CS0218: The type ('T') must contain declarations of operator true and operator false // I have changed that to: // CS0218: In order to be applicable as a short circuit operator, the declaring type // '{1}' of user-defined operator '{0}' must declare operator true and operator false. Error(diagnostics, ErrorCode.ERR_MustHaveOpTF, syntax, signature.Method, t); diagnostics.Add(syntax, useSiteInfo); trueOperator = null; falseOperator = null; return false; } diagnostics.Add(syntax, useSiteInfo); // For the remainder of this method the comments WOLOG assume that we're analyzing an &&. The // exact same issues apply to ||. // Note that the mere *existence* of operator true and operator false is sufficient. They // are already constrained to take either T or T?. Since we know that the applicable // T.& takes (T, T), we know that both sides of the && are implicitly convertible // to T, and therefore the left side is implicitly convertible to T or T?. // SPEC: The expression x && y is evaluated as T.false(x) ? x : T.&(x,y) ... except that // SPEC: x is only evaluated once. // // DELIBERATE SPEC VIOLATION: The native compiler does not actually evaluate x&&y in this // manner. Suppose X is of type X. The code above is equivalent to: // // X temp = x, then evaluate: // T.false(temp) ? temp : T.&(temp, y) // // What the native compiler actually evaluates is: // // T temp = x, then evaluate // T.false(temp) ? temp : T.&(temp, y) // // That is a small difference but it has an observable effect. For example: // // class V { public static implicit operator T(V v) { ... } } // class X : V { public static implicit operator T?(X x) { ... } } // struct T { // public static operator false(T? t) { ... } // public static operator true(T? t) { ... } // public static T operator &(T t1, T t2) { ... } // } // // Under the spec'd interpretation, if we had x of type X and y of type T then x && y is // // X temp = x; // T.false(temp) ? temp : T.&(temp, y) // // which would then be analyzed as: // // T.false(X.op_Implicit_To_Nullable_T(temp)) ? // V.op_Implicit_To_T(temp) : // T.&(op_Implicit_To_T(temp), y) // // But the native compiler actually generates: // // T temp = V.Op_Implicit_To_T(x); // T.false(new T?(temp)) ? temp : T.&(temp, y) // // That is, the native compiler converts the temporary to the type of the declaring operator type // regardless of the fact that there is a better conversion for the T.false call. // // We choose to match the native compiler behavior here; we might consider fixing // the spec to match the compiler. // // With this decision we need not keep track of any extra information in the bound // binary operator node; we need to know the left hand side converted to T, the right // hand side converted to T, and the method symbol of the chosen T.&(T, T) method. // The rewriting pass has enough information to deduce which T.false is to be called, // and can convert the T to T? if necessary. return true; } private bool HasApplicableBooleanOperator(NamedTypeSymbol containingType, string name, TypeSymbol argumentType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out MethodSymbol @operator) { for (var type = containingType; (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { var operators = type.GetOperators(name); for (var i = 0; i < operators.Length; i++) { var op = operators[i]; if (op.ParameterCount == 1 && op.DeclaredAccessibility == Accessibility.Public) { var conversion = this.Conversions.ClassifyConversionFromType(argumentType, op.GetParameterType(0), ref useSiteInfo); if (conversion.IsImplicit) { @operator = op; return true; } } } } @operator = null; return false; } private TypeSymbol GetBinaryOperatorErrorType(BinaryOperatorKind kind, BindingDiagnosticBag diagnostics, CSharpSyntaxNode node) { switch (kind) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: return GetSpecialType(SpecialType.System_Boolean, diagnostics, node); default: return CreateErrorType(); } } private BinaryOperatorAnalysisResult BinaryOperatorOverloadResolution(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators) { if (!IsTypelessExpressionAllowedInBinaryOperator(kind, left, right)) { resultKind = LookupResultKind.OverloadResolutionFailure; originalUserDefinedOperators = default(ImmutableArray<MethodSymbol>); return default(BinaryOperatorAnalysisResult); } var result = BinaryOperatorOverloadResolutionResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.OverloadResolution.BinaryOperatorOverloadResolution(kind, left, right, result, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); var possiblyBest = result.Best; if (result.Results.Any()) { var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var analysisResult in result.Results) { MethodSymbol method = analysisResult.Signature.Method; if ((object)method != null) { builder.Add(method); } } originalUserDefinedOperators = builder.ToImmutableAndFree(); if (possiblyBest.HasValue) { resultKind = LookupResultKind.Viable; } else if (result.AnyValid()) { resultKind = LookupResultKind.Ambiguous; } else { resultKind = LookupResultKind.OverloadResolutionFailure; } } else { originalUserDefinedOperators = ImmutableArray<MethodSymbol>.Empty; resultKind = possiblyBest.HasValue ? LookupResultKind.Viable : LookupResultKind.Empty; } if (possiblyBest is { HasValue: true, Signature: { Method: { } bestMethod } }) { ReportObsoleteAndFeatureAvailabilityDiagnostics(bestMethod, node, diagnostics); ReportUseSite(bestMethod, diagnostics, node); } result.Free(); return possiblyBest; } private void ReportObsoleteAndFeatureAvailabilityDiagnostics(MethodSymbol operatorMethod, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { if ((object)operatorMethod != null) { ReportDiagnosticsIfObsolete(diagnostics, operatorMethod, node, hasBaseReceiver: false); if (operatorMethod.ContainingType.IsInterface && operatorMethod.ContainingModule != Compilation.SourceModule) { Binder.CheckFeatureAvailability(node, MessageID.IDS_DefaultInterfaceImplementation, diagnostics); } } } private bool IsTypelessExpressionAllowedInBinaryOperator(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { // The default literal is only allowed with equality operators and both operands cannot be typeless at the same time. // Note: we only need to restrict expressions that can be converted to *any* type, in which case the resolution could always succeed. if (left.IsImplicitObjectCreation() || right.IsImplicitObjectCreation()) { return false; } bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual; if (isEquality) { return !left.IsLiteralDefault() || !right.IsLiteralDefault(); } else { return !left.IsLiteralDefault() && !right.IsLiteralDefault(); } } private UnaryOperatorAnalysisResult UnaryOperatorOverloadResolution( UnaryOperatorKind kind, BoundExpression operand, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators) { var result = UnaryOperatorOverloadResolutionResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.OverloadResolution.UnaryOperatorOverloadResolution(kind, operand, result, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); var possiblyBest = result.Best; if (result.Results.Any()) { var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var analysisResult in result.Results) { MethodSymbol method = analysisResult.Signature.Method; if ((object)method != null) { builder.Add(method); } } originalUserDefinedOperators = builder.ToImmutableAndFree(); if (possiblyBest.HasValue) { resultKind = LookupResultKind.Viable; } else if (result.AnyValid()) { // Special case: If we have the unary minus operator applied to a ulong, technically that should be // an ambiguity. The ulong could be implicitly converted to float, double or decimal, and then // the unary minus operator could be applied to the result. But though float is better than double, // float is neither better nor worse than decimal. However it seems odd to give an ambiguity error // when trying to do something such as applying a unary minus operator to an unsigned long. // The same issue applies to unary minus applied to nuint. if (kind == UnaryOperatorKind.UnaryMinus && (object)operand.Type != null && (operand.Type.SpecialType == SpecialType.System_UInt64 || (operand.Type.SpecialType == SpecialType.System_UIntPtr && operand.Type.IsNativeIntegerType))) { resultKind = LookupResultKind.OverloadResolutionFailure; } else { resultKind = LookupResultKind.Ambiguous; } } else { resultKind = LookupResultKind.OverloadResolutionFailure; } } else { originalUserDefinedOperators = ImmutableArray<MethodSymbol>.Empty; resultKind = possiblyBest.HasValue ? LookupResultKind.Viable : LookupResultKind.Empty; } if (possiblyBest is { HasValue: true, Signature: { Method: { } bestMethod } }) { ReportObsoleteAndFeatureAvailabilityDiagnostics(bestMethod, node, diagnostics); ReportUseSite(bestMethod, diagnostics, node); } result.Free(); return possiblyBest; } private static object FoldDecimalBinaryOperators(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); // Roslyn uses Decimal.operator+, operator-, etc. for both constant expressions and // non-constant expressions. Dev11 uses Decimal.operator+ etc. for non-constant // expressions only. This leads to different results between the two compilers // for certain constant expressions involving +/-0. (See bug #529730.) For instance, // +0 + -0 == +0 in Roslyn and == -0 in Dev11. Similarly, -0 - -0 == -0 in Roslyn, +0 in Dev11. // This is a breaking change from the native compiler but seems acceptable since // constant and non-constant expressions behave consistently in Roslyn. // (In Dev11, (+0 + -0) != (x + y) when x = +0, y = -0.) switch (kind) { case BinaryOperatorKind.DecimalAddition: return valueLeft.DecimalValue + valueRight.DecimalValue; case BinaryOperatorKind.DecimalSubtraction: return valueLeft.DecimalValue - valueRight.DecimalValue; case BinaryOperatorKind.DecimalMultiplication: return valueLeft.DecimalValue * valueRight.DecimalValue; case BinaryOperatorKind.DecimalDivision: return valueLeft.DecimalValue / valueRight.DecimalValue; case BinaryOperatorKind.DecimalRemainder: return valueLeft.DecimalValue % valueRight.DecimalValue; } return null; } private static object FoldNativeIntegerOverflowingBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); checked { switch (kind) { case BinaryOperatorKind.NIntAddition: return valueLeft.Int32Value + valueRight.Int32Value; case BinaryOperatorKind.NUIntAddition: return valueLeft.UInt32Value + valueRight.UInt32Value; case BinaryOperatorKind.NIntSubtraction: return valueLeft.Int32Value - valueRight.Int32Value; case BinaryOperatorKind.NUIntSubtraction: return valueLeft.UInt32Value - valueRight.UInt32Value; case BinaryOperatorKind.NIntMultiplication: return valueLeft.Int32Value * valueRight.Int32Value; case BinaryOperatorKind.NUIntMultiplication: return valueLeft.UInt32Value * valueRight.UInt32Value; case BinaryOperatorKind.NIntDivision: return valueLeft.Int32Value / valueRight.Int32Value; case BinaryOperatorKind.NIntRemainder: return valueLeft.Int32Value % valueRight.Int32Value; case BinaryOperatorKind.NIntLeftShift: { var int32Value = valueLeft.Int32Value << valueRight.Int32Value; var int64Value = valueLeft.Int64Value << valueRight.Int32Value; return (int32Value == int64Value) ? int32Value : null; } case BinaryOperatorKind.NUIntLeftShift: { var uint32Value = valueLeft.UInt32Value << valueRight.Int32Value; var uint64Value = valueLeft.UInt64Value << valueRight.Int32Value; return (uint32Value == uint64Value) ? uint32Value : null; } } return null; } } private static object FoldUncheckedIntegralBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); unchecked { switch (kind) { case BinaryOperatorKind.IntAddition: return valueLeft.Int32Value + valueRight.Int32Value; case BinaryOperatorKind.LongAddition: return valueLeft.Int64Value + valueRight.Int64Value; case BinaryOperatorKind.UIntAddition: return valueLeft.UInt32Value + valueRight.UInt32Value; case BinaryOperatorKind.ULongAddition: return valueLeft.UInt64Value + valueRight.UInt64Value; case BinaryOperatorKind.IntSubtraction: return valueLeft.Int32Value - valueRight.Int32Value; case BinaryOperatorKind.LongSubtraction: return valueLeft.Int64Value - valueRight.Int64Value; case BinaryOperatorKind.UIntSubtraction: return valueLeft.UInt32Value - valueRight.UInt32Value; case BinaryOperatorKind.ULongSubtraction: return valueLeft.UInt64Value - valueRight.UInt64Value; case BinaryOperatorKind.IntMultiplication: return valueLeft.Int32Value * valueRight.Int32Value; case BinaryOperatorKind.LongMultiplication: return valueLeft.Int64Value * valueRight.Int64Value; case BinaryOperatorKind.UIntMultiplication: return valueLeft.UInt32Value * valueRight.UInt32Value; case BinaryOperatorKind.ULongMultiplication: return valueLeft.UInt64Value * valueRight.UInt64Value; // even in unchecked context division may overflow: case BinaryOperatorKind.IntDivision: if (valueLeft.Int32Value == int.MinValue && valueRight.Int32Value == -1) { return int.MinValue; } return valueLeft.Int32Value / valueRight.Int32Value; case BinaryOperatorKind.LongDivision: if (valueLeft.Int64Value == long.MinValue && valueRight.Int64Value == -1) { return long.MinValue; } return valueLeft.Int64Value / valueRight.Int64Value; } return null; } } private static object FoldCheckedIntegralBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); checked { switch (kind) { case BinaryOperatorKind.IntAddition: return valueLeft.Int32Value + valueRight.Int32Value; case BinaryOperatorKind.LongAddition: return valueLeft.Int64Value + valueRight.Int64Value; case BinaryOperatorKind.UIntAddition: return valueLeft.UInt32Value + valueRight.UInt32Value; case BinaryOperatorKind.ULongAddition: return valueLeft.UInt64Value + valueRight.UInt64Value; case BinaryOperatorKind.IntSubtraction: return valueLeft.Int32Value - valueRight.Int32Value; case BinaryOperatorKind.LongSubtraction: return valueLeft.Int64Value - valueRight.Int64Value; case BinaryOperatorKind.UIntSubtraction: return valueLeft.UInt32Value - valueRight.UInt32Value; case BinaryOperatorKind.ULongSubtraction: return valueLeft.UInt64Value - valueRight.UInt64Value; case BinaryOperatorKind.IntMultiplication: return valueLeft.Int32Value * valueRight.Int32Value; case BinaryOperatorKind.LongMultiplication: return valueLeft.Int64Value * valueRight.Int64Value; case BinaryOperatorKind.UIntMultiplication: return valueLeft.UInt32Value * valueRight.UInt32Value; case BinaryOperatorKind.ULongMultiplication: return valueLeft.UInt64Value * valueRight.UInt64Value; case BinaryOperatorKind.IntDivision: return valueLeft.Int32Value / valueRight.Int32Value; case BinaryOperatorKind.LongDivision: return valueLeft.Int64Value / valueRight.Int64Value; } return null; } } internal static TypeSymbol GetEnumType(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { switch (kind) { case BinaryOperatorKind.EnumAndUnderlyingAddition: case BinaryOperatorKind.EnumAndUnderlyingSubtraction: case BinaryOperatorKind.EnumAnd: case BinaryOperatorKind.EnumOr: case BinaryOperatorKind.EnumXor: case BinaryOperatorKind.EnumEqual: case BinaryOperatorKind.EnumGreaterThan: case BinaryOperatorKind.EnumGreaterThanOrEqual: case BinaryOperatorKind.EnumLessThan: case BinaryOperatorKind.EnumLessThanOrEqual: case BinaryOperatorKind.EnumNotEqual: case BinaryOperatorKind.EnumSubtraction: return left.Type; case BinaryOperatorKind.UnderlyingAndEnumAddition: case BinaryOperatorKind.UnderlyingAndEnumSubtraction: return right.Type; default: throw ExceptionUtilities.UnexpectedValue(kind); } } internal static SpecialType GetEnumPromotedType(SpecialType underlyingType) { switch (underlyingType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: return SpecialType.System_Int32; case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return underlyingType; default: throw ExceptionUtilities.UnexpectedValue(underlyingType); } } #nullable enable private ConstantValue? FoldEnumBinaryOperator( CSharpSyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) { Debug.Assert(left != null); Debug.Assert(right != null); Debug.Assert(kind.IsEnum()); Debug.Assert(!kind.IsLifted()); // A built-in binary operation on constant enum operands is evaluated into an operation on // constants of the underlying type U of the enum type E. Comparison operators are lowered as // simply computing U<U. All other operators are computed as (E)(U op U) or in the case of // E-E, (U)(U-U). TypeSymbol enumType = GetEnumType(kind, left, right); TypeSymbol underlyingType = enumType.GetEnumUnderlyingType()!; BoundExpression newLeftOperand = CreateConversion(left, underlyingType, diagnostics); BoundExpression newRightOperand = CreateConversion(right, underlyingType, diagnostics); // If the underlying type is byte, sbyte, short, ushort or nullables of those then we'll need // to convert it up to int or int? because there are no + - * & | ^ < > <= >= == != operators // on byte, sbyte, short or ushort. They all convert to int. SpecialType operandSpecialType = GetEnumPromotedType(underlyingType.SpecialType); TypeSymbol operandType = (operandSpecialType == underlyingType.SpecialType) ? underlyingType : GetSpecialType(operandSpecialType, diagnostics, syntax); newLeftOperand = CreateConversion(newLeftOperand, operandType, diagnostics); newRightOperand = CreateConversion(newRightOperand, operandType, diagnostics); BinaryOperatorKind newKind = kind.Operator().WithType(newLeftOperand.Type!.SpecialType); switch (newKind.Operator()) { case BinaryOperatorKind.Addition: case BinaryOperatorKind.Subtraction: case BinaryOperatorKind.And: case BinaryOperatorKind.Or: case BinaryOperatorKind.Xor: resultTypeSymbol = operandType; break; case BinaryOperatorKind.LessThan: case BinaryOperatorKind.LessThanOrEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: Debug.Assert(resultTypeSymbol.SpecialType == SpecialType.System_Boolean); break; default: throw ExceptionUtilities.UnexpectedValue(newKind.Operator()); } var constantValue = FoldBinaryOperator(syntax, newKind, newLeftOperand, newRightOperand, resultTypeSymbol, diagnostics); if (resultTypeSymbol.SpecialType != SpecialType.System_Boolean && constantValue != null && !constantValue.IsBad) { TypeSymbol resultType = kind == BinaryOperatorKind.EnumSubtraction ? underlyingType : enumType; // We might need to convert back to the underlying type. return FoldConstantNumericConversion(syntax, constantValue, resultType, diagnostics); } return constantValue; } // Returns null if the operator can't be evaluated at compile time. private ConstantValue? FoldBinaryOperator( CSharpSyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) { Debug.Assert(left != null); Debug.Assert(right != null); if (left.HasAnyErrors || right.HasAnyErrors) { return null; } // SPEC VIOLATION: see method definition for details ConstantValue? nullableEqualityResult = TryFoldingNullableEquality(kind, left, right); if (nullableEqualityResult != null) { return nullableEqualityResult; } var valueLeft = left.ConstantValue; var valueRight = right.ConstantValue; if (valueLeft == null || valueRight == null) { return null; } if (valueLeft.IsBad || valueRight.IsBad) { return ConstantValue.Bad; } if (kind.IsEnum() && !kind.IsLifted()) { return FoldEnumBinaryOperator(syntax, kind, left, right, resultTypeSymbol, diagnostics); } // Divisions by zero on integral types and decimal always fail even in an unchecked context. if (IsDivisionByZero(kind, valueRight)) { Error(diagnostics, ErrorCode.ERR_IntDivByZero, syntax); return ConstantValue.Bad; } object? newValue = null; SpecialType resultType = resultTypeSymbol.SpecialType; // Certain binary operations never fail; bool & bool, for example. If we are in one of those // cases, simply fold the operation and return. // // Although remainder and division always overflow at runtime with arguments int.MinValue/long.MinValue and -1 // (regardless of checked context) the constant folding behavior is different. // Remainder never overflows at compile time while division does. newValue = FoldNeverOverflowBinaryOperators(kind, valueLeft, valueRight); if (newValue != null) { return ConstantValue.Create(newValue, resultType); } ConstantValue? concatResult = FoldStringConcatenation(kind, valueLeft, valueRight); if (concatResult != null) { if (concatResult.IsBad) { Error(diagnostics, ErrorCode.ERR_ConstantStringTooLong, right.Syntax); } return concatResult; } // Certain binary operations always fail if they overflow even when in an unchecked context; // decimal + decimal, for example. If we are in one of those cases, make the attempt. If it // succeeds, return the result. If not, give a compile-time error regardless of context. try { newValue = FoldDecimalBinaryOperators(kind, valueLeft, valueRight); } catch (OverflowException) { Error(diagnostics, ErrorCode.ERR_DecConstError, syntax); return ConstantValue.Bad; } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } try { newValue = FoldNativeIntegerOverflowingBinaryOperator(kind, valueLeft, valueRight); } catch (OverflowException) { if (CheckOverflowAtCompileTime) { Error(diagnostics, ErrorCode.WRN_CompileTimeCheckedOverflow, syntax, resultTypeSymbol); } return null; } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } if (CheckOverflowAtCompileTime) { try { newValue = FoldCheckedIntegralBinaryOperator(kind, valueLeft, valueRight); } catch (OverflowException) { Error(diagnostics, ErrorCode.ERR_CheckedOverflow, syntax); return ConstantValue.Bad; } } else { newValue = FoldUncheckedIntegralBinaryOperator(kind, valueLeft, valueRight); } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } return null; } /// <summary> /// If one of the (unconverted) operands has constant value null and the other has /// a null constant value other than null, then they are definitely not equal /// and we can give a constant value for either == or !=. This is a spec violation /// that we retain from Dev10. /// </summary> /// <param name="kind">The operator kind. Nothing will happen if it is not a lifted equality operator.</param> /// <param name="left">The left-hand operand of the operation (possibly wrapped in a conversion).</param> /// <param name="right">The right-hand operand of the operation (possibly wrapped in a conversion).</param> /// <returns> /// If the operator represents lifted equality, then constant value true if both arguments have constant /// value null, constant value false if exactly one argument has constant value null, and null otherwise. /// If the operator represents lifted inequality, then constant value false if both arguments have constant /// value null, constant value true if exactly one argument has constant value null, and null otherwise. /// </returns> /// <remarks> /// SPEC VIOLATION: according to the spec (section 7.19) constant expressions cannot /// include implicit nullable conversions or nullable subexpressions. However, Dev10 /// specifically folds over lifted == and != (see ExpressionBinder::TryFoldingNullableEquality). /// Dev 10 does do compile-time evaluation of simple lifted operators, but it does so /// in a rewriting pass (see NullableRewriter) - they are not treated as constant values. /// </remarks> private static ConstantValue? TryFoldingNullableEquality(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { if (kind.IsLifted()) { BinaryOperatorKind op = kind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { if (left.Kind == BoundKind.Conversion && right.Kind == BoundKind.Conversion) { BoundConversion leftConv = (BoundConversion)left; BoundConversion rightConv = (BoundConversion)right; ConstantValue? leftConstant = leftConv.Operand.ConstantValue; ConstantValue? rightConstant = rightConv.Operand.ConstantValue; if (leftConstant != null && rightConstant != null) { bool leftIsNull = leftConstant.IsNull; bool rightIsNull = rightConstant.IsNull; if (leftIsNull || rightIsNull) { // IMPL CHANGE: Dev10 raises WRN_NubExprIsConstBool in some cases, but that really doesn't // make sense (why warn that a constant has a constant value?). return (leftIsNull == rightIsNull) == (op == BinaryOperatorKind.Equal) ? ConstantValue.True : ConstantValue.False; } } } } } return null; } // Some binary operators on constants never overflow, regardless of whether the context is checked or not. private static object? FoldNeverOverflowBinaryOperators(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); // Note that we *cannot* do folding on single-precision floats as doubles to preserve precision, // as that would cause incorrect rounding that would be impossible to correct afterwards. switch (kind) { case BinaryOperatorKind.ObjectEqual: if (valueLeft.IsNull) return valueRight.IsNull; if (valueRight.IsNull) return false; break; case BinaryOperatorKind.ObjectNotEqual: if (valueLeft.IsNull) return !valueRight.IsNull; if (valueRight.IsNull) return true; break; case BinaryOperatorKind.DoubleAddition: return valueLeft.DoubleValue + valueRight.DoubleValue; case BinaryOperatorKind.FloatAddition: return valueLeft.SingleValue + valueRight.SingleValue; case BinaryOperatorKind.DoubleSubtraction: return valueLeft.DoubleValue - valueRight.DoubleValue; case BinaryOperatorKind.FloatSubtraction: return valueLeft.SingleValue - valueRight.SingleValue; case BinaryOperatorKind.DoubleMultiplication: return valueLeft.DoubleValue * valueRight.DoubleValue; case BinaryOperatorKind.FloatMultiplication: return valueLeft.SingleValue * valueRight.SingleValue; case BinaryOperatorKind.DoubleDivision: return valueLeft.DoubleValue / valueRight.DoubleValue; case BinaryOperatorKind.FloatDivision: return valueLeft.SingleValue / valueRight.SingleValue; case BinaryOperatorKind.DoubleRemainder: return valueLeft.DoubleValue % valueRight.DoubleValue; case BinaryOperatorKind.FloatRemainder: return valueLeft.SingleValue % valueRight.SingleValue; case BinaryOperatorKind.IntLeftShift: return valueLeft.Int32Value << valueRight.Int32Value; case BinaryOperatorKind.LongLeftShift: return valueLeft.Int64Value << valueRight.Int32Value; case BinaryOperatorKind.UIntLeftShift: return valueLeft.UInt32Value << valueRight.Int32Value; case BinaryOperatorKind.ULongLeftShift: return valueLeft.UInt64Value << valueRight.Int32Value; case BinaryOperatorKind.IntRightShift: case BinaryOperatorKind.NIntRightShift: return valueLeft.Int32Value >> valueRight.Int32Value; case BinaryOperatorKind.LongRightShift: return valueLeft.Int64Value >> valueRight.Int32Value; case BinaryOperatorKind.UIntRightShift: case BinaryOperatorKind.NUIntRightShift: return valueLeft.UInt32Value >> valueRight.Int32Value; case BinaryOperatorKind.ULongRightShift: return valueLeft.UInt64Value >> valueRight.Int32Value; case BinaryOperatorKind.BoolAnd: return valueLeft.BooleanValue & valueRight.BooleanValue; case BinaryOperatorKind.IntAnd: case BinaryOperatorKind.NIntAnd: return valueLeft.Int32Value & valueRight.Int32Value; case BinaryOperatorKind.LongAnd: return valueLeft.Int64Value & valueRight.Int64Value; case BinaryOperatorKind.UIntAnd: case BinaryOperatorKind.NUIntAnd: return valueLeft.UInt32Value & valueRight.UInt32Value; case BinaryOperatorKind.ULongAnd: return valueLeft.UInt64Value & valueRight.UInt64Value; case BinaryOperatorKind.BoolOr: return valueLeft.BooleanValue | valueRight.BooleanValue; case BinaryOperatorKind.IntOr: case BinaryOperatorKind.NIntOr: return valueLeft.Int32Value | valueRight.Int32Value; case BinaryOperatorKind.LongOr: return valueLeft.Int64Value | valueRight.Int64Value; case BinaryOperatorKind.UIntOr: case BinaryOperatorKind.NUIntOr: return valueLeft.UInt32Value | valueRight.UInt32Value; case BinaryOperatorKind.ULongOr: return valueLeft.UInt64Value | valueRight.UInt64Value; case BinaryOperatorKind.BoolXor: return valueLeft.BooleanValue ^ valueRight.BooleanValue; case BinaryOperatorKind.IntXor: case BinaryOperatorKind.NIntXor: return valueLeft.Int32Value ^ valueRight.Int32Value; case BinaryOperatorKind.LongXor: return valueLeft.Int64Value ^ valueRight.Int64Value; case BinaryOperatorKind.UIntXor: case BinaryOperatorKind.NUIntXor: return valueLeft.UInt32Value ^ valueRight.UInt32Value; case BinaryOperatorKind.ULongXor: return valueLeft.UInt64Value ^ valueRight.UInt64Value; case BinaryOperatorKind.LogicalBoolAnd: return valueLeft.BooleanValue && valueRight.BooleanValue; case BinaryOperatorKind.LogicalBoolOr: return valueLeft.BooleanValue || valueRight.BooleanValue; case BinaryOperatorKind.BoolEqual: return valueLeft.BooleanValue == valueRight.BooleanValue; case BinaryOperatorKind.StringEqual: return valueLeft.StringValue == valueRight.StringValue; case BinaryOperatorKind.DecimalEqual: return valueLeft.DecimalValue == valueRight.DecimalValue; case BinaryOperatorKind.FloatEqual: return valueLeft.SingleValue == valueRight.SingleValue; case BinaryOperatorKind.DoubleEqual: return valueLeft.DoubleValue == valueRight.DoubleValue; case BinaryOperatorKind.IntEqual: case BinaryOperatorKind.NIntEqual: return valueLeft.Int32Value == valueRight.Int32Value; case BinaryOperatorKind.LongEqual: return valueLeft.Int64Value == valueRight.Int64Value; case BinaryOperatorKind.UIntEqual: case BinaryOperatorKind.NUIntEqual: return valueLeft.UInt32Value == valueRight.UInt32Value; case BinaryOperatorKind.ULongEqual: return valueLeft.UInt64Value == valueRight.UInt64Value; case BinaryOperatorKind.BoolNotEqual: return valueLeft.BooleanValue != valueRight.BooleanValue; case BinaryOperatorKind.StringNotEqual: return valueLeft.StringValue != valueRight.StringValue; case BinaryOperatorKind.DecimalNotEqual: return valueLeft.DecimalValue != valueRight.DecimalValue; case BinaryOperatorKind.FloatNotEqual: return valueLeft.SingleValue != valueRight.SingleValue; case BinaryOperatorKind.DoubleNotEqual: return valueLeft.DoubleValue != valueRight.DoubleValue; case BinaryOperatorKind.IntNotEqual: case BinaryOperatorKind.NIntNotEqual: return valueLeft.Int32Value != valueRight.Int32Value; case BinaryOperatorKind.LongNotEqual: return valueLeft.Int64Value != valueRight.Int64Value; case BinaryOperatorKind.UIntNotEqual: case BinaryOperatorKind.NUIntNotEqual: return valueLeft.UInt32Value != valueRight.UInt32Value; case BinaryOperatorKind.ULongNotEqual: return valueLeft.UInt64Value != valueRight.UInt64Value; case BinaryOperatorKind.DecimalLessThan: return valueLeft.DecimalValue < valueRight.DecimalValue; case BinaryOperatorKind.FloatLessThan: return valueLeft.SingleValue < valueRight.SingleValue; case BinaryOperatorKind.DoubleLessThan: return valueLeft.DoubleValue < valueRight.DoubleValue; case BinaryOperatorKind.IntLessThan: case BinaryOperatorKind.NIntLessThan: return valueLeft.Int32Value < valueRight.Int32Value; case BinaryOperatorKind.LongLessThan: return valueLeft.Int64Value < valueRight.Int64Value; case BinaryOperatorKind.UIntLessThan: case BinaryOperatorKind.NUIntLessThan: return valueLeft.UInt32Value < valueRight.UInt32Value; case BinaryOperatorKind.ULongLessThan: return valueLeft.UInt64Value < valueRight.UInt64Value; case BinaryOperatorKind.DecimalGreaterThan: return valueLeft.DecimalValue > valueRight.DecimalValue; case BinaryOperatorKind.FloatGreaterThan: return valueLeft.SingleValue > valueRight.SingleValue; case BinaryOperatorKind.DoubleGreaterThan: return valueLeft.DoubleValue > valueRight.DoubleValue; case BinaryOperatorKind.IntGreaterThan: case BinaryOperatorKind.NIntGreaterThan: return valueLeft.Int32Value > valueRight.Int32Value; case BinaryOperatorKind.LongGreaterThan: return valueLeft.Int64Value > valueRight.Int64Value; case BinaryOperatorKind.UIntGreaterThan: case BinaryOperatorKind.NUIntGreaterThan: return valueLeft.UInt32Value > valueRight.UInt32Value; case BinaryOperatorKind.ULongGreaterThan: return valueLeft.UInt64Value > valueRight.UInt64Value; case BinaryOperatorKind.DecimalLessThanOrEqual: return valueLeft.DecimalValue <= valueRight.DecimalValue; case BinaryOperatorKind.FloatLessThanOrEqual: return valueLeft.SingleValue <= valueRight.SingleValue; case BinaryOperatorKind.DoubleLessThanOrEqual: return valueLeft.DoubleValue <= valueRight.DoubleValue; case BinaryOperatorKind.IntLessThanOrEqual: case BinaryOperatorKind.NIntLessThanOrEqual: return valueLeft.Int32Value <= valueRight.Int32Value; case BinaryOperatorKind.LongLessThanOrEqual: return valueLeft.Int64Value <= valueRight.Int64Value; case BinaryOperatorKind.UIntLessThanOrEqual: case BinaryOperatorKind.NUIntLessThanOrEqual: return valueLeft.UInt32Value <= valueRight.UInt32Value; case BinaryOperatorKind.ULongLessThanOrEqual: return valueLeft.UInt64Value <= valueRight.UInt64Value; case BinaryOperatorKind.DecimalGreaterThanOrEqual: return valueLeft.DecimalValue >= valueRight.DecimalValue; case BinaryOperatorKind.FloatGreaterThanOrEqual: return valueLeft.SingleValue >= valueRight.SingleValue; case BinaryOperatorKind.DoubleGreaterThanOrEqual: return valueLeft.DoubleValue >= valueRight.DoubleValue; case BinaryOperatorKind.IntGreaterThanOrEqual: case BinaryOperatorKind.NIntGreaterThanOrEqual: return valueLeft.Int32Value >= valueRight.Int32Value; case BinaryOperatorKind.LongGreaterThanOrEqual: return valueLeft.Int64Value >= valueRight.Int64Value; case BinaryOperatorKind.UIntGreaterThanOrEqual: case BinaryOperatorKind.NUIntGreaterThanOrEqual: return valueLeft.UInt32Value >= valueRight.UInt32Value; case BinaryOperatorKind.ULongGreaterThanOrEqual: return valueLeft.UInt64Value >= valueRight.UInt64Value; case BinaryOperatorKind.UIntDivision: case BinaryOperatorKind.NUIntDivision: return valueLeft.UInt32Value / valueRight.UInt32Value; case BinaryOperatorKind.ULongDivision: return valueLeft.UInt64Value / valueRight.UInt64Value; // MinValue % -1 always overflows at runtime but never at compile time case BinaryOperatorKind.IntRemainder: return (valueRight.Int32Value != -1) ? valueLeft.Int32Value % valueRight.Int32Value : 0; case BinaryOperatorKind.LongRemainder: return (valueRight.Int64Value != -1) ? valueLeft.Int64Value % valueRight.Int64Value : 0; case BinaryOperatorKind.UIntRemainder: case BinaryOperatorKind.NUIntRemainder: return valueLeft.UInt32Value % valueRight.UInt32Value; case BinaryOperatorKind.ULongRemainder: return valueLeft.UInt64Value % valueRight.UInt64Value; } return null; } /// <summary> /// Returns ConstantValue.Bad if, and only if, the resulting string length exceeds <see cref="int.MaxValue"/>. /// </summary> private static ConstantValue? FoldStringConcatenation(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) { Debug.Assert(valueLeft != null); Debug.Assert(valueRight != null); if (kind == BinaryOperatorKind.StringConcatenation) { Rope leftValue = valueLeft.RopeValue ?? Rope.Empty; Rope rightValue = valueRight.RopeValue ?? Rope.Empty; long newLength = (long)leftValue.Length + (long)rightValue.Length; return (newLength > int.MaxValue) ? ConstantValue.Bad : ConstantValue.CreateFromRope(Rope.Concat(leftValue, rightValue)); } return null; } #nullable disable private static BinaryOperatorKind SyntaxKindToBinaryOperatorKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.MultiplyExpression: return BinaryOperatorKind.Multiplication; case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.DivideExpression: return BinaryOperatorKind.Division; case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.ModuloExpression: return BinaryOperatorKind.Remainder; case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AddExpression: return BinaryOperatorKind.Addition; case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.SubtractExpression: return BinaryOperatorKind.Subtraction; case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.RightShiftExpression: return BinaryOperatorKind.RightShift; case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.LeftShiftExpression: return BinaryOperatorKind.LeftShift; case SyntaxKind.EqualsExpression: return BinaryOperatorKind.Equal; case SyntaxKind.NotEqualsExpression: return BinaryOperatorKind.NotEqual; case SyntaxKind.GreaterThanExpression: return BinaryOperatorKind.GreaterThan; case SyntaxKind.LessThanExpression: return BinaryOperatorKind.LessThan; case SyntaxKind.GreaterThanOrEqualExpression: return BinaryOperatorKind.GreaterThanOrEqual; case SyntaxKind.LessThanOrEqualExpression: return BinaryOperatorKind.LessThanOrEqual; case SyntaxKind.AndAssignmentExpression: case SyntaxKind.BitwiseAndExpression: return BinaryOperatorKind.And; case SyntaxKind.OrAssignmentExpression: case SyntaxKind.BitwiseOrExpression: return BinaryOperatorKind.Or; case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.ExclusiveOrExpression: return BinaryOperatorKind.Xor; case SyntaxKind.LogicalAndExpression: return BinaryOperatorKind.LogicalAnd; case SyntaxKind.LogicalOrExpression: return BinaryOperatorKind.LogicalOr; default: throw ExceptionUtilities.UnexpectedValue(kind); } } private BoundExpression BindIncrementOperator(CSharpSyntaxNode node, ExpressionSyntax operandSyntax, SyntaxToken operatorToken, BindingDiagnosticBag diagnostics) { operandSyntax.CheckDeconstructionCompatibleArgument(diagnostics); BoundExpression operand = BindToNaturalType(BindValue(operandSyntax, diagnostics, BindValueKind.IncrementDecrement), diagnostics); UnaryOperatorKind kind = SyntaxKindToUnaryOperatorKind(node.Kind()); // If the operand is bad, avoid generating cascading errors. if (operand.HasAnyErrors) { // NOTE: no candidate user-defined operators. return new BoundIncrementOperator( node, kind, operand, methodOpt: null, constrainedToTypeOpt: null, Conversion.NoConversion, Conversion.NoConversion, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); } // The operand has to be a variable, property or indexer, so it must have a type. var operandType = operand.Type; Debug.Assert((object)operandType != null); if (operandType.IsDynamic()) { return new BoundIncrementOperator( node, kind.WithType(UnaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), operand, methodOpt: null, constrainedToTypeOpt: null, operandConversion: Conversion.NoConversion, resultConversion: Conversion.NoConversion, resultKind: LookupResultKind.Viable, originalUserDefinedOperatorsOpt: default(ImmutableArray<MethodSymbol>), type: operandType, hasErrors: false); } LookupResultKind resultKind; ImmutableArray<MethodSymbol> originalUserDefinedOperators; var best = this.UnaryOperatorOverloadResolution(kind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); if (!best.HasValue) { ReportUnaryOperatorError(node, diagnostics, operatorToken.Text, operand, resultKind); return new BoundIncrementOperator( node, kind, operand, methodOpt: null, constrainedToTypeOpt: null, Conversion.NoConversion, Conversion.NoConversion, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); } var signature = best.Signature; CheckNativeIntegerFeatureAvailability(signature.Kind, node, diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resultConversion = Conversions.ClassifyConversionFromType(signature.ReturnType, operandType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); bool hasErrors = false; if (!resultConversion.IsImplicit || !resultConversion.IsValid) { GenerateImplicitConversionError(diagnostics, this.Compilation, node, resultConversion, signature.ReturnType, operandType); hasErrors = true; } else { ReportDiagnosticsIfObsolete(diagnostics, resultConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, resultConversion, diagnostics); } if (!hasErrors && operandType.IsVoidPointer()) { Error(diagnostics, ErrorCode.ERR_VoidError, node); hasErrors = true; } Conversion operandConversion = best.Conversion; ReportDiagnosticsIfObsolete(diagnostics, operandConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, operandConversion, diagnostics); return new BoundIncrementOperator( node, signature.Kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), operand, signature.Method, signature.ConstrainedToTypeOpt, operandConversion, resultConversion, resultKind, originalUserDefinedOperators, operandType, hasErrors); } #nullable enable /// <summary> /// Returns false if reported an error, true otherwise. /// </summary> private bool CheckConstraintLanguageVersionAndRuntimeSupportForOperator(SyntaxNode node, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, BindingDiagnosticBag diagnostics) { bool result = true; if (methodOpt?.ContainingType?.IsInterface == true && methodOpt.IsStatic) { if (methodOpt.IsAbstract) { if (constrainedToTypeOpt is not TypeParameterSymbol) { Error(diagnostics, ErrorCode.ERR_BadAbstractStaticMemberAccess, node); return false; } if (Compilation.SourceModule != methodOpt.ContainingModule) { result = CheckFeatureAvailability(node, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, node); return false; } } } else if (methodOpt.Name is WellKnownMemberNames.EqualityOperatorName or WellKnownMemberNames.InequalityOperatorName) { result = CheckFeatureAvailability(node, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); } } return result; } #nullable disable private BoundExpression BindSuppressNullableWarningExpression(PostfixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { var expr = BindExpression(node.Operand, diagnostics); switch (expr.Kind) { case BoundKind.NamespaceExpression: case BoundKind.TypeExpression: Error(diagnostics, ErrorCode.ERR_IllegalSuppression, expr.Syntax); break; default: if (expr.IsSuppressed) { Debug.Assert(node.Operand.SkipParens().GetLastToken().Kind() == SyntaxKind.ExclamationToken); Error(diagnostics, ErrorCode.ERR_DuplicateNullSuppression, expr.Syntax); } break; } return expr.WithSuppression(); } // Based on ExpressionBinder::bindPtrIndirection. private BoundExpression BindPointerIndirectionExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = BindToNaturalType(BindValue(node.Operand, diagnostics, GetUnaryAssignmentKind(node.Kind())), diagnostics); TypeSymbol pointedAtType; bool hasErrors; BindPointerIndirectionExpressionInternal(node, operand, diagnostics, out pointedAtType, out hasErrors); return new BoundPointerIndirectionOperator(node, operand, pointedAtType ?? CreateErrorType(), hasErrors); } private static void BindPointerIndirectionExpressionInternal(CSharpSyntaxNode node, BoundExpression operand, BindingDiagnosticBag diagnostics, out TypeSymbol pointedAtType, out bool hasErrors) { var operandType = operand.Type as PointerTypeSymbol; hasErrors = operand.HasAnyErrors; // This would propagate automatically, but by reading it explicitly we can reduce cascading. if ((object)operandType == null) { pointedAtType = null; if (!hasErrors) { // NOTE: Dev10 actually reports ERR_BadUnaryOp if the operand has Type == null, // but this seems clearer. Error(diagnostics, ErrorCode.ERR_PtrExpected, node); hasErrors = true; } } else { pointedAtType = operandType.PointedAtType; if (pointedAtType.IsVoidType()) { pointedAtType = null; if (!hasErrors) { Error(diagnostics, ErrorCode.ERR_VoidError, node); hasErrors = true; } } } } // Based on ExpressionBinder::bindPtrAddr. private BoundExpression BindAddressOfExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = BindToNaturalType(BindValue(node.Operand, diagnostics, BindValueKind.AddressOf), diagnostics); ReportSuppressionIfNeeded(operand, diagnostics); bool hasErrors = operand.HasAnyErrors; // This would propagate automatically, but by reading it explicitly we can reduce cascading. bool isFixedStatementAddressOfExpression = SyntaxFacts.IsFixedStatementExpression(node); switch (operand) { case BoundLambda _: case UnboundLambda _: { Debug.Assert(hasErrors); return new BoundAddressOfOperator(node, operand, CreateErrorType(), hasErrors: true); } case BoundMethodGroup methodGroup: return new BoundUnconvertedAddressOfOperator(node, methodGroup, hasErrors); } TypeSymbol operandType = operand.Type; Debug.Assert((object)operandType != null, "BindValue should have caught a null operand type"); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); ManagedKind managedKind = operandType.GetManagedKind(ref useSiteInfo); diagnostics.Add(node.Location, useSiteInfo); bool allowManagedAddressOf = Flags.Includes(BinderFlags.AllowManagedAddressOf); if (!allowManagedAddressOf) { if (!hasErrors) { hasErrors = CheckManagedAddr(Compilation, operandType, managedKind, node.Location, diagnostics); } if (!hasErrors) { Symbol accessedLocalOrParameterOpt; if (IsMoveableVariable(operand, out accessedLocalOrParameterOpt) != isFixedStatementAddressOfExpression) { Error(diagnostics, isFixedStatementAddressOfExpression ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedNeeded, node); hasErrors = true; } } } TypeSymbol pointedAtType = managedKind == ManagedKind.Managed && allowManagedAddressOf ? GetSpecialType(SpecialType.System_IntPtr, diagnostics, node) : operandType ?? CreateErrorType(); TypeSymbol pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(pointedAtType)); return new BoundAddressOfOperator(node, operand, pointerType, hasErrors); } /// <summary> /// Checks to see whether an expression is a "moveable" variable according to the spec. Moveable /// variables have underlying memory which may be moved by the runtime. The spec defines anything /// not fixed as moveable and specifies the expressions which are fixed. /// </summary> internal bool IsMoveableVariable(BoundExpression expr, out Symbol accessedLocalOrParameterOpt) { accessedLocalOrParameterOpt = null; while (true) { BoundKind exprKind = expr.Kind; switch (exprKind) { case BoundKind.FieldAccess: case BoundKind.EventAccess: { FieldSymbol fieldSymbol; BoundExpression receiver; if (exprKind == BoundKind.FieldAccess) { BoundFieldAccess fieldAccess = (BoundFieldAccess)expr; fieldSymbol = fieldAccess.FieldSymbol; receiver = fieldAccess.ReceiverOpt; } else { BoundEventAccess eventAccess = (BoundEventAccess)expr; if (!eventAccess.IsUsableAsField || eventAccess.EventSymbol.IsWindowsRuntimeEvent) { return true; } EventSymbol eventSymbol = eventAccess.EventSymbol; fieldSymbol = eventSymbol.AssociatedField; receiver = eventAccess.ReceiverOpt; } if ((object)fieldSymbol == null || fieldSymbol.IsStatic || (object)receiver == null) { return true; } bool receiverIsLValue = CheckValueKind(receiver.Syntax, receiver, BindValueKind.AddressOf, checkingReceiver: false, diagnostics: BindingDiagnosticBag.Discarded); if (!receiverIsLValue) { return true; } // NOTE: type parameters will already have been weeded out, since a // variable of type parameter type has to be cast to an effective // base or interface type before its fields can be accessed and a // conversion isn't an lvalue. if (receiver.Type.IsReferenceType) { return true; } expr = receiver; continue; } case BoundKind.RangeVariable: { // NOTE: there are cases where you can take the address of a range variable. // e.g. from x in new int[3] select *(&x) BoundRangeVariable variableAccess = (BoundRangeVariable)expr; expr = variableAccess.Value; //Check the underlying expression. continue; } case BoundKind.Parameter: { BoundParameter parameterAccess = (BoundParameter)expr; ParameterSymbol parameterSymbol = parameterAccess.ParameterSymbol; accessedLocalOrParameterOpt = parameterSymbol; return parameterSymbol.RefKind != RefKind.None; } case BoundKind.ThisReference: case BoundKind.BaseReference: { accessedLocalOrParameterOpt = this.ContainingMemberOrLambda.EnclosingThisSymbol(); return true; } case BoundKind.Local: { BoundLocal localAccess = (BoundLocal)expr; LocalSymbol localSymbol = localAccess.LocalSymbol; accessedLocalOrParameterOpt = localSymbol; // NOTE: The spec says that this is moveable if it is captured by an anonymous function, // but that will be reported separately and error-recovery is better if we say that // such locals are not moveable. return localSymbol.RefKind != RefKind.None; } case BoundKind.PointerIndirectionOperator: //Covers ->, since the receiver will be one of these. case BoundKind.ConvertedStackAllocExpression: { return false; } case BoundKind.PointerElementAccess: { // C# 7.3: // a variable resulting from a... pointer_element_access of the form P[E] [is fixed] if P // is not a fixed size buffer expression, or if the expression is a fixed size buffer // member_access of the form E.I and E is a fixed variable BoundExpression underlyingExpr = ((BoundPointerElementAccess)expr).Expression; if (underlyingExpr is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { expr = fieldAccess.ReceiverOpt; continue; } return false; } case BoundKind.PropertyAccess: // Never fixed case BoundKind.IndexerAccess: // Never fixed default: { return true; } } } } private BoundExpression BindUnaryOperator(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = BindToNaturalType(BindValue(node.Operand, diagnostics, GetUnaryAssignmentKind(node.Kind())), diagnostics); BoundLiteral constant = BindIntegralMinValConstants(node, operand, diagnostics); return constant ?? BindUnaryOperatorCore(node, node.OperatorToken.Text, operand, diagnostics); } private void ReportSuppressionIfNeeded(BoundExpression expr, BindingDiagnosticBag diagnostics) { if (expr.IsSuppressed) { Error(diagnostics, ErrorCode.ERR_IllegalSuppression, expr.Syntax); } } #nullable enable private BoundExpression BindUnaryOperatorCore(CSharpSyntaxNode node, string operatorText, BoundExpression operand, BindingDiagnosticBag diagnostics) { UnaryOperatorKind kind = SyntaxKindToUnaryOperatorKind(node.Kind()); bool isOperandNullOrNew = operand.IsLiteralNull() || operand.IsImplicitObjectCreation(); if (isOperandNullOrNew) { // Dev10 does not allow unary prefix operators to be applied to the null literal // (or other typeless expressions). Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorText, operand.Display); } // If the operand is bad, avoid generating cascading errors. if (isOperandNullOrNew || operand.Type?.IsErrorType() == true) { // Note: no candidate user-defined operators. return new BoundUnaryOperator(node, kind, operand, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Empty, type: CreateErrorType(), hasErrors: true); } // If the operand is dynamic then we do not attempt to do overload resolution at compile // time; we defer that until runtime. If we did overload resolution then the dynamic // operand would be implicitly convertible to the parameter type of each operator // signature, and therefore every operator would be an applicable candidate. Instead // of changing overload resolution to handle dynamic, we just handle it here and let // overload resolution implement the specification. if (operand.HasDynamicType()) { return new BoundUnaryOperator( syntax: node, operatorKind: kind.WithType(UnaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), operand: operand, constantValueOpt: ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, type: operand.Type!); } LookupResultKind resultKind; ImmutableArray<MethodSymbol> originalUserDefinedOperators; var best = this.UnaryOperatorOverloadResolution(kind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); if (!best.HasValue) { ReportUnaryOperatorError(node, diagnostics, operatorText, operand, resultKind); return new BoundUnaryOperator( node, kind, operand, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); } var signature = best.Signature; var resultOperand = CreateConversion(operand.Syntax, operand, best.Conversion, isCast: false, conversionGroupOpt: null, signature.OperandType, diagnostics); var resultType = signature.ReturnType; UnaryOperatorKind resultOperatorKind = signature.Kind; var resultConstant = FoldUnaryOperator(node, resultOperatorKind, resultOperand, resultType, diagnostics); CheckNativeIntegerFeatureAvailability(resultOperatorKind, node, diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); return new BoundUnaryOperator( node, resultOperatorKind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), resultOperand, resultConstant, signature.Method, signature.ConstrainedToTypeOpt, resultKind, resultType); } private ConstantValue? FoldEnumUnaryOperator( CSharpSyntaxNode syntax, UnaryOperatorKind kind, BoundExpression operand, BindingDiagnosticBag diagnostics) { var underlyingType = operand.Type.GetEnumUnderlyingType()!; BoundExpression newOperand = CreateConversion(operand, underlyingType, diagnostics); // We may have to upconvert the type if it is a byte, sbyte, short, ushort // or nullable of those, because there is no ~ operator var upconvertSpecialType = GetEnumPromotedType(underlyingType.SpecialType); var upconvertType = upconvertSpecialType == underlyingType.SpecialType ? underlyingType : GetSpecialType(upconvertSpecialType, diagnostics, syntax); newOperand = CreateConversion(newOperand, upconvertType, diagnostics); UnaryOperatorKind newKind = kind.Operator().WithType(upconvertSpecialType); var constantValue = FoldUnaryOperator(syntax, newKind, operand, upconvertType, diagnostics); // Convert back to the underlying type if (constantValue != null && !constantValue.IsBad) { // Do an unchecked conversion if bitwise complement var binder = kind.Operator() == UnaryOperatorKind.BitwiseComplement ? this.WithCheckedOrUncheckedRegion(@checked: false) : this; return binder.FoldConstantNumericConversion(syntax, constantValue, underlyingType, diagnostics); } return constantValue; } private ConstantValue? FoldUnaryOperator( CSharpSyntaxNode syntax, UnaryOperatorKind kind, BoundExpression operand, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) { Debug.Assert(operand != null); // UNDONE: report errors when in a checked context. if (operand.HasAnyErrors) { return null; } var value = operand.ConstantValue; if (value == null || value.IsBad) { return value; } if (kind.IsEnum() && !kind.IsLifted()) { return FoldEnumUnaryOperator(syntax, kind, operand, diagnostics); } SpecialType resultType = resultTypeSymbol.SpecialType; var newValue = FoldNeverOverflowUnaryOperator(kind, value); if (newValue != null) { return ConstantValue.Create(newValue, resultType); } try { newValue = FoldNativeIntegerOverflowingUnaryOperator(kind, value); } catch (OverflowException) { if (CheckOverflowAtCompileTime) { Error(diagnostics, ErrorCode.WRN_CompileTimeCheckedOverflow, syntax, resultTypeSymbol); } return null; } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } if (CheckOverflowAtCompileTime) { try { newValue = FoldCheckedIntegralUnaryOperator(kind, value); } catch (OverflowException) { Error(diagnostics, ErrorCode.ERR_CheckedOverflow, syntax); return ConstantValue.Bad; } } else { newValue = FoldUncheckedIntegralUnaryOperator(kind, value); } if (newValue != null) { return ConstantValue.Create(newValue, resultType); } return null; } private static object? FoldNeverOverflowUnaryOperator(UnaryOperatorKind kind, ConstantValue value) { // Note that we do operations on single-precision floats as double-precision. switch (kind) { case UnaryOperatorKind.DecimalUnaryMinus: return -value.DecimalValue; case UnaryOperatorKind.DoubleUnaryMinus: case UnaryOperatorKind.FloatUnaryMinus: return -value.DoubleValue; case UnaryOperatorKind.DecimalUnaryPlus: return +value.DecimalValue; case UnaryOperatorKind.FloatUnaryPlus: case UnaryOperatorKind.DoubleUnaryPlus: return +value.DoubleValue; case UnaryOperatorKind.LongUnaryPlus: return +value.Int64Value; case UnaryOperatorKind.ULongUnaryPlus: return +value.UInt64Value; case UnaryOperatorKind.IntUnaryPlus: case UnaryOperatorKind.NIntUnaryPlus: return +value.Int32Value; case UnaryOperatorKind.UIntUnaryPlus: case UnaryOperatorKind.NUIntUnaryPlus: return +value.UInt32Value; case UnaryOperatorKind.BoolLogicalNegation: return !value.BooleanValue; case UnaryOperatorKind.IntBitwiseComplement: return ~value.Int32Value; case UnaryOperatorKind.LongBitwiseComplement: return ~value.Int64Value; case UnaryOperatorKind.UIntBitwiseComplement: return ~value.UInt32Value; case UnaryOperatorKind.ULongBitwiseComplement: return ~value.UInt64Value; } return null; } private static object? FoldUncheckedIntegralUnaryOperator(UnaryOperatorKind kind, ConstantValue value) { unchecked { switch (kind) { case UnaryOperatorKind.LongUnaryMinus: return -value.Int64Value; case UnaryOperatorKind.IntUnaryMinus: return -value.Int32Value; } } return null; } private static object? FoldCheckedIntegralUnaryOperator(UnaryOperatorKind kind, ConstantValue value) { checked { switch (kind) { case UnaryOperatorKind.LongUnaryMinus: return -value.Int64Value; case UnaryOperatorKind.IntUnaryMinus: return -value.Int32Value; } } return null; } private static object? FoldNativeIntegerOverflowingUnaryOperator(UnaryOperatorKind kind, ConstantValue value) { checked { switch (kind) { case UnaryOperatorKind.NIntUnaryMinus: return -value.Int32Value; case UnaryOperatorKind.NIntBitwiseComplement: case UnaryOperatorKind.NUIntBitwiseComplement: return null; } } return null; } private static UnaryOperatorKind SyntaxKindToUnaryOperatorKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.PreIncrementExpression: return UnaryOperatorKind.PrefixIncrement; case SyntaxKind.PostIncrementExpression: return UnaryOperatorKind.PostfixIncrement; case SyntaxKind.PreDecrementExpression: return UnaryOperatorKind.PrefixDecrement; case SyntaxKind.PostDecrementExpression: return UnaryOperatorKind.PostfixDecrement; case SyntaxKind.UnaryPlusExpression: return UnaryOperatorKind.UnaryPlus; case SyntaxKind.UnaryMinusExpression: return UnaryOperatorKind.UnaryMinus; case SyntaxKind.LogicalNotExpression: return UnaryOperatorKind.LogicalNegation; case SyntaxKind.BitwiseNotExpression: return UnaryOperatorKind.BitwiseComplement; default: throw ExceptionUtilities.UnexpectedValue(kind); } } private static BindValueKind GetBinaryAssignmentKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.SimpleAssignmentExpression: return BindValueKind.Assignable; case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: return BindValueKind.CompoundAssignment; default: return BindValueKind.RValue; } } private static BindValueKind GetUnaryAssignmentKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.PreDecrementExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.PostIncrementExpression: return BindValueKind.IncrementDecrement; case SyntaxKind.AddressOfExpression: Debug.Assert(false, "Should be handled separately."); goto default; default: return BindValueKind.RValue; } } #nullable disable private BoundLiteral BindIntegralMinValConstants(PrefixUnaryExpressionSyntax node, BoundExpression operand, BindingDiagnosticBag diagnostics) { // SPEC: To permit the smallest possible int and long values to be written as decimal integer // SPEC: literals, the following two rules exist: // SPEC: When a decimal-integer-literal with the value 2147483648 and no integer-type-suffix // SPEC: appears as the token immediately following a unary minus operator token, the result is a // SPEC: constant of type int with the value −2147483648. // SPEC: When a decimal-integer-literal with the value 9223372036854775808 and no integer-type-suffix // SPEC: or the integer-type-suffix L or l appears as the token immediately following a unary minus // SPEC: operator token, the result is a constant of type long with the value −9223372036854775808. if (node.Kind() != SyntaxKind.UnaryMinusExpression) { return null; } if (node.Operand != operand.Syntax || operand.Syntax.Kind() != SyntaxKind.NumericLiteralExpression) { return null; } var literal = (LiteralExpressionSyntax)operand.Syntax; var token = literal.Token; if (token.Value is uint) { uint value = (uint)token.Value; if (value != 2147483648U) { return null; } if (token.Text.Contains("u") || token.Text.Contains("U") || token.Text.Contains("l") || token.Text.Contains("L")) { return null; } return new BoundLiteral(node, ConstantValue.Create((int)-2147483648), GetSpecialType(SpecialType.System_Int32, diagnostics, node)); } else if (token.Value is ulong) { var value = (ulong)token.Value; if (value != 9223372036854775808UL) { return null; } if (token.Text.Contains("u") || token.Text.Contains("U")) { return null; } return new BoundLiteral(node, ConstantValue.Create(-9223372036854775808), GetSpecialType(SpecialType.System_Int64, diagnostics, node)); } return null; } private static bool IsDivisionByZero(BinaryOperatorKind kind, ConstantValue valueRight) { Debug.Assert(valueRight != null); switch (kind) { case BinaryOperatorKind.DecimalDivision: case BinaryOperatorKind.DecimalRemainder: return valueRight.DecimalValue == 0.0m; case BinaryOperatorKind.IntDivision: case BinaryOperatorKind.IntRemainder: case BinaryOperatorKind.NIntDivision: case BinaryOperatorKind.NIntRemainder: return valueRight.Int32Value == 0; case BinaryOperatorKind.LongDivision: case BinaryOperatorKind.LongRemainder: return valueRight.Int64Value == 0; case BinaryOperatorKind.UIntDivision: case BinaryOperatorKind.UIntRemainder: case BinaryOperatorKind.NUIntDivision: case BinaryOperatorKind.NUIntRemainder: return valueRight.UInt32Value == 0; case BinaryOperatorKind.ULongDivision: case BinaryOperatorKind.ULongRemainder: return valueRight.UInt64Value == 0; } return false; } private bool IsOperandErrors(CSharpSyntaxNode node, ref BoundExpression operand, BindingDiagnosticBag diagnostics) { switch (operand.Kind) { case BoundKind.UnboundLambda: case BoundKind.Lambda: case BoundKind.MethodGroup: // New in Roslyn - see DevDiv #864740. // operand for an is or as expression cannot be a lambda expression or method group if (!operand.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_LambdaInIsAs, node); } operand = BadExpression(node, operand).MakeCompilerGenerated(); return true; default: if ((object)operand.Type == null && !operand.IsLiteralNull()) { if (!operand.HasAnyErrors) { // Operator 'is' cannot be applied to operand of type '(int, <null>)' Error(diagnostics, ErrorCode.ERR_BadUnaryOp, node, SyntaxFacts.GetText(SyntaxKind.IsKeyword), operand.Display); } operand = BadExpression(node, operand).MakeCompilerGenerated(); return true; } break; } return operand.HasAnyErrors; } private bool IsOperatorErrors(CSharpSyntaxNode node, TypeSymbol operandType, BoundTypeExpression typeExpression, BindingDiagnosticBag diagnostics) { var targetType = typeExpression.Type; // The native compiler allows "x is C" where C is a static class. This // is strictly illegal according to the specification (see the section // called "Referencing Static Class Types".) To retain compatibility we // allow it, but when /warn:5 or higher we break with the native // compiler and turn this into a warning. if (targetType.IsStatic) { Error(diagnostics, ErrorCode.WRN_StaticInAsOrIs, node, targetType); } if ((object)operandType != null && operandType.IsPointerOrFunctionPointer() || targetType.IsPointerOrFunctionPointer()) { // operand for an is or as expression cannot be of pointer type Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, node); return true; } return targetType.TypeKind == TypeKind.Error; } protected static bool IsUnderscore(ExpressionSyntax node) => node is IdentifierNameSyntax name && name.Identifier.IsUnderscoreToken(); private BoundExpression BindIsOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { var resultType = (TypeSymbol)GetSpecialType(SpecialType.System_Boolean, diagnostics, node); var operand = BindRValueWithoutTargetType(node.Left, diagnostics); var operandHasErrors = IsOperandErrors(node, ref operand, diagnostics); // try binding as a type, but back off to binding as an expression if that does not work. bool wasUnderscore = IsUnderscore(node.Right); if (!tryBindAsType(node.Right, diagnostics, out BindingDiagnosticBag isTypeDiagnostics, out BoundTypeExpression typeExpression) && !wasUnderscore && ((CSharpParseOptions)node.SyntaxTree.Options).IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching)) { // it did not bind as a type; try binding as a constant expression pattern var isPatternDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); if ((object)operand.Type == null) { if (!operandHasErrors) { isPatternDiagnostics.Add(ErrorCode.ERR_BadPatternExpression, node.Left.Location, operand.Display); } operand = ToBadExpression(operand); } bool hasErrors = node.Right.HasErrors; var convertedExpression = BindExpressionForPattern(operand.Type, node.Right, ref hasErrors, isPatternDiagnostics, out var constantValueOpt, out var wasExpression); if (wasExpression) { hasErrors |= constantValueOpt is null; isTypeDiagnostics.Free(); diagnostics.AddRangeAndFree(isPatternDiagnostics); var boundConstantPattern = new BoundConstantPattern( node.Right, convertedExpression, constantValueOpt ?? ConstantValue.Bad, operand.Type, convertedExpression.Type ?? operand.Type, hasErrors) #pragma warning disable format { WasCompilerGenerated = true }; #pragma warning restore format return MakeIsPatternExpression(node, operand, boundConstantPattern, resultType, operandHasErrors, diagnostics); } isPatternDiagnostics.Free(); } diagnostics.AddRangeAndFree(isTypeDiagnostics); var targetTypeWithAnnotations = typeExpression.TypeWithAnnotations; var targetType = typeExpression.Type; if (targetType.IsReferenceType && targetTypeWithAnnotations.NullableAnnotation.IsAnnotated()) { Error(diagnostics, ErrorCode.ERR_IsNullableType, node.Right, targetType); operandHasErrors = true; } var targetTypeKind = targetType.TypeKind; if (operandHasErrors || IsOperatorErrors(node, operand.Type, typeExpression, diagnostics)) { return new BoundIsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } if (wasUnderscore && ((CSharpParseOptions)node.SyntaxTree.Options).IsFeatureEnabled(MessageID.IDS_FeatureRecursivePatterns)) { diagnostics.Add(ErrorCode.WRN_IsTypeNamedUnderscore, node.Right.Location, typeExpression.AliasOpt ?? (Symbol)targetType); } // Is and As operator should have null ConstantValue as they are not constant expressions. // However we perform analysis of is/as expressions at bind time to detect if the expression // will always evaluate to a constant to generate warnings (always true/false/null). // We also need this analysis result during rewrite to optimize away redundant isinst instructions. // We store the conversion from expression's operand type to target type to enable these // optimizations during is/as operator rewrite. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (operand.ConstantValue == ConstantValue.Null || operand.Kind == BoundKind.MethodGroup || operand.Type.IsVoidType()) { // warning for cases where the result is always false: // (a) "null is TYPE" OR operand evaluates to null // (b) operand is a MethodGroup // (c) operand is of void type // NOTE: Dev10 violates the SPEC for case (c) above and generates // NOTE: an error ERR_NoExplicitBuiltinConv if the target type // NOTE: is an open type. According to the specification, the result // NOTE: is always false, but no compile time error occurs. // NOTE: We follow the specification and generate WRN_IsAlwaysFalse // NOTE: instead of an error. // NOTE: See Test SyntaxBinderTests.TestIsOperatorWithTypeParameter Error(diagnostics, ErrorCode.WRN_IsAlwaysFalse, node, targetType); Conversion conv = Conversions.ClassifyConversionFromExpression(operand, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); return new BoundIsOperator(node, operand, typeExpression, conv, resultType); } if (targetTypeKind == TypeKind.Dynamic) { // warning for dynamic target type Error(diagnostics, ErrorCode.WRN_IsDynamicIsConfusing, node, node.OperatorToken.Text, targetType.Name, GetSpecialType(SpecialType.System_Object, diagnostics, node).Name // a pretty way of getting the string "Object" ); } var operandType = operand.Type; Debug.Assert((object)operandType != null); if (operandType.TypeKind == TypeKind.Dynamic) { // if operand has a dynamic type, we do the same thing as though it were an object operandType = GetSpecialType(SpecialType.System_Object, diagnostics, node); } Conversion conversion = Conversions.ClassifyBuiltInConversion(operandType, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); ReportIsOperatorConstantWarnings(node, diagnostics, operandType, targetType, conversion.Kind, operand.ConstantValue); return new BoundIsOperator(node, operand, typeExpression, conversion, resultType); bool tryBindAsType( ExpressionSyntax possibleType, BindingDiagnosticBag diagnostics, out BindingDiagnosticBag bindAsTypeDiagnostics, out BoundTypeExpression boundType) { bindAsTypeDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); TypeWithAnnotations targetTypeWithAnnotations = BindType(possibleType, bindAsTypeDiagnostics, out AliasSymbol alias); TypeSymbol targetType = targetTypeWithAnnotations.Type; boundType = new BoundTypeExpression(possibleType, alias, targetTypeWithAnnotations); return !(targetType?.IsErrorType() == true && bindAsTypeDiagnostics.HasAnyResolvedErrors()); } } private static void ReportIsOperatorConstantWarnings( CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) { // NOTE: Even though BoundIsOperator and BoundAsOperator will always have no ConstantValue // NOTE: (they are non-constant expressions according to Section 7.19 of the specification), // NOTE: we want to perform constant analysis of is/as expressions to generate warnings if the // NOTE: expression will always be true/false/null. ConstantValue constantValue = GetIsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); if (constantValue != null) { Debug.Assert(constantValue == ConstantValue.True || constantValue == ConstantValue.False); ErrorCode errorCode = constantValue == ConstantValue.True ? ErrorCode.WRN_IsAlwaysTrue : ErrorCode.WRN_IsAlwaysFalse; Error(diagnostics, errorCode, syntax, targetType); } } internal static ConstantValue GetIsOperatorConstantResult( TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue, bool operandCouldBeNull = true) { Debug.Assert((object)targetType != null); // SPEC: The result of the operation depends on D and T as follows: // SPEC: 1) If T is a reference type, the result is true if D and T are the same type, if D is a reference type and // SPEC: an implicit reference conversion from D to T exists, or if D is a value type and a boxing conversion from D to T exists. // SPEC: 2) If T is a nullable type, the result is true if D is the underlying type of T. // SPEC: 3) If T is a non-nullable value type, the result is true if D and T are the same type. // SPEC: 4) Otherwise, the result is false. // NOTE: The language specification talks about the runtime evaluation of the is operation. // NOTE: However, we are interested in computing the compile time constant value for the expression. // NOTE: Even though BoundIsOperator and BoundAsOperator will always have no ConstantValue // NOTE: (they are non-constant expressions according to Section 7.19 of the specification), // NOTE: we want to perform constant analysis of is/as expressions during binding to generate warnings // NOTE: (always true/false/null) and during rewriting for optimized codegen. // NOTE: // NOTE: Because the heuristic presented here is used to change codegen, it must be conservative. It is acceptable // NOTE: for us to fail to report a warning in cases where humans could logically deduce that the operator will // NOTE: always return false. It is not acceptable to inaccurately warn that the operator will always return false // NOTE: if there are cases where it might succeed. // NOTE: // NOTE: These same heuristics are also used in pattern-matching to determine if an expression of the form // NOTE: `e is T x` is permitted. It is an error if `e` cannot be of type `T` according to this method // NOTE: returning ConstantValue.False. // NOTE: The heuristics are also used to determine if a `case T1 x1:` is subsumed by // NOTE: some previous `case T2 x2:` in a switch statement. For that purpose operandType is T1, targetType is T2, // NOTE: and operandCouldBeNull is false; the former subsumes the latter if this method returns ConstantValue.True. // NOTE: Since the heuristic is now used to produce errors in pattern-matching, making it more accurate in the // NOTE: future could be a breaking change. // To begin our heuristic: if the operand is literal null then we automatically return that the // result is false. You might think that we can simply check to see if the conversion is // ConversionKind.NullConversion, but "null is T" for a type parameter T is actually classified // as an implicit reference conversion if T is constrained to reference types. Rather // than deal with all those special cases we can simply bail out here. if (operandConstantValue == ConstantValue.Null) { return ConstantValue.False; } Debug.Assert((object)operandType != null); operandCouldBeNull = operandCouldBeNull && operandType.CanContainNull() && // a non-nullable value type is never null (operandConstantValue == null || operandConstantValue == ConstantValue.Null); // a non-null constant is never null switch (conversionKind) { case ConversionKind.NoConversion: // Oddly enough, "x is T" can be true even if there is no conversion from x to T! // // Scenario 1: Type parameter compared to System.Enum. // // bool M1<X>(X x) where X : struct { return x is Enum; } // // There is no conversion from X to Enum, not even an explicit conversion. But // nevertheless, X could be constructed as an enumerated type. // However, we can sometimes know that the result will be false. // // Scenario 2a: Constrained type parameter compared to reference type. // // bool M2a<X>(X x) where X : struct { return x is string; } // // We know that X, constrained to struct, will never be string. // // Scenario 2b: Reference type compared to constrained type parameter. // // bool M2b<X>(string x) where X : struct { return x is X; } // // We know that string will never be X, constrained to struct. // // Scenario 3: Value type compared to type parameter. // // bool M3<T>(int x) { return x is T; } // // There is no conversion from int to T, but T could nevertheless be int. // // Scenario 4: Constructed type compared to open type // // bool M4<T>(C<int> x) { return x is C<T>; } // // There is no conversion from C<int> to C<T>, but nevertheless, T might be int. // // Scenario 5: Open type compared to constructed type: // // bool M5<X>(C<X> x) { return x is C<int>); // // Again, X could be int. // // We could then go on to get more complicated. For example, // // bool M6<X>(C<X> x) where X : struct { return x is C<string>; } // // We know that C<X> is never convertible to C<string> no matter what // X is. Or: // // bool M7<T>(Dictionary<int, int> x) { return x is List<T>; } // // We know that no matter what T is, the conversion will never succeed. // // As noted above, we must be conservative. We follow the lead of the native compiler, // which uses the following algorithm: // // * If neither type is open and there is no conversion then the result is always false: if (!operandType.ContainsTypeParameter() && !targetType.ContainsTypeParameter()) { return ConstantValue.False; } // * Otherwise, at least one of them is of an open type. If the operand is of value type // and the target is a class type other than System.Enum, or vice versa, then we are // in scenario 2, not scenario 1, and can correctly deduce that the result is false. if (operandType.IsValueType && targetType.IsClassType() && targetType.SpecialType != SpecialType.System_Enum || targetType.IsValueType && operandType.IsClassType() && operandType.SpecialType != SpecialType.System_Enum) { return ConstantValue.False; } // * Otherwise, if the other type is a restricted type, we know no conversion is possible. if (targetType.IsRestrictedType() || operandType.IsRestrictedType()) { return ConstantValue.False; } // * Otherwise, we give up. Though there are other situations in which we can deduce that // the result will always be false, such as scenarios 6 and 7, but we do not attempt // to deduce this. // CONSIDER: we could use TypeUnification.CanUnify to do additional compile-time checking. return null; case ConversionKind.ImplicitNumeric: case ConversionKind.ExplicitNumeric: case ConversionKind.ImplicitEnumeration: // case ConversionKind.ExplicitEnumeration: // Handled separately below. case ConversionKind.ImplicitConstant: case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: case ConversionKind.IntPtr: case ConversionKind.ExplicitTuple: case ConversionKind.ImplicitTuple: // Consider all the cases where we know that "x is T" must be false just from // the conversion classification. // // If we have "x is T" and the conversion from x to T is numeric or enum then the result must be false. // // If we have "null is T" then obviously that must be false. // // If we have "1 is long" then that must be false. (If we have "1 is int" then it is an identity conversion, // not an implicit constant conversion. // // User-defined and IntPtr conversions are always false for "is". return ConstantValue.False; case ConversionKind.ExplicitEnumeration: // Enum-to-enum conversions should be treated the same as unsuccessful struct-to-struct // conversions (i.e. make allowances for type unification, etc) if (operandType.IsEnumType() && targetType.IsEnumType()) { goto case ConversionKind.NoConversion; } return ConstantValue.False; case ConversionKind.ExplicitNullable: // An explicit nullable conversion is a conversion of one of the following forms: // // 1) X? --> Y?, where X --> Y is an explicit conversion. (If X --> Y is an implicit // conversion then X? --> Y? is an implicit nullable conversion.) In this case we // know that "X? is Y?" must be false because either X? is null, or we have an // explicit conversion from struct type X to struct type Y, and so X is never of type Y.) // // 2) X --> Y?, where again, X --> Y is an explicit conversion. By the same reasoning // as in case 1, this must be false. if (targetType.IsNullableType()) { return ConstantValue.False; } Debug.Assert(operandType.IsNullableType()); // 3) X? --> X. In this case, this is just a different way of writing "x != null". // We only know what the result will be if the input is known not to be null. if (Conversions.HasIdentityConversion(operandType.GetNullableUnderlyingType(), targetType)) { return operandCouldBeNull ? null : ConstantValue.True; } // 4) X? --> Y where the conversion X --> Y is an implicit or explicit value type conversion. // "X? is Y" again must be false. return ConstantValue.False; case ConversionKind.ImplicitReference: return operandCouldBeNull ? null : ConstantValue.True; case ConversionKind.ExplicitReference: case ConversionKind.Unboxing: // In these three cases, the expression type must be a reference type. Therefore, // the result cannot be determined. The expression could be null or of the wrong type, // resulting in false, or it could be a non-null reference to the appropriate type, // resulting in true. return null; case ConversionKind.Identity: // The result of "x is T" can be statically determined to be true if x is an expression // of non-nullable value type T. If x is of reference or nullable value type then // we cannot know, because again, the expression value could be null or it could be good. // If it is of pointer type then we have already given an error. return operandCouldBeNull ? null : ConstantValue.True; case ConversionKind.Boxing: // A boxing conversion might be a conversion: // // * From a non-nullable value type to a reference type // * From a nullable value type to a reference type // * From a type parameter that *could* be a value type under construction // to a reference type // // In the first case we know that the conversion will always succeed and that the // operand is never null, and therefore "is" will always result in true. // // In the second two cases we do not know; either the nullable value type could be // null, or the type parameter could be constructed with a reference type, and it // could be null. return operandCouldBeNull ? null : ConstantValue.True; case ConversionKind.ImplicitNullable: // We have "x is T" in one of the following situations: // 1) x is of type X and T is X?. The value is always true. // 2) x is of type X and T is Y? where X is convertible to Y via an implicit numeric conversion. Eg, // x is of type int and T is decimal?. The value is always false. // 3) x is of type X? and T is Y? where X is convertible to Y via an implicit numeric conversion. // The value is always false. Debug.Assert(targetType.IsNullableType()); return operandType.Equals(targetType.GetNullableUnderlyingType(), TypeCompareKind.AllIgnoreOptions) ? ConstantValue.True : ConstantValue.False; default: case ConversionKind.ImplicitDynamic: case ConversionKind.ExplicitDynamic: case ConversionKind.ExplicitPointerToInteger: case ConversionKind.ExplicitPointerToPointer: case ConversionKind.ImplicitPointerToVoid: case ConversionKind.ExplicitIntegerToPointer: case ConversionKind.ImplicitNullToPointer: case ConversionKind.AnonymousFunction: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.MethodGroup: // We've either replaced Dynamic with Object, or already bailed out with an error. throw ExceptionUtilities.UnexpectedValue(conversionKind); } } private BoundExpression BindAsOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { var operand = BindRValueWithoutTargetType(node.Left, diagnostics); AliasSymbol alias; TypeWithAnnotations targetTypeWithAnnotations = BindType(node.Right, diagnostics, out alias); TypeSymbol targetType = targetTypeWithAnnotations.Type; var typeExpression = new BoundTypeExpression(node.Right, alias, targetTypeWithAnnotations); var targetTypeKind = targetType.TypeKind; var resultType = targetType; // Is and As operator should have null ConstantValue as they are not constant expressions. // However we perform analysis of is/as expressions at bind time to detect if the expression // will always evaluate to a constant to generate warnings (always true/false/null). // We also need this analysis result during rewrite to optimize away redundant isinst instructions. // We store the conversion kind from expression's operand type to target type to enable these // optimizations during is/as operator rewrite. switch (operand.Kind) { case BoundKind.UnboundLambda: case BoundKind.Lambda: case BoundKind.MethodGroup: // New in Roslyn - see DevDiv #864740. // operand for an is or as expression cannot be a lambda expression or method group if (!operand.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_LambdaInIsAs, node); } return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: if ((object)operand.Type == null) { Error(diagnostics, ErrorCode.ERR_TypelessTupleInAs, node); return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } break; } if (operand.HasAnyErrors || targetTypeKind == TypeKind.Error) { // If either operand is bad or target type has errors, bail out preventing more cascading errors. return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } if (targetType.IsReferenceType && targetTypeWithAnnotations.NullableAnnotation.IsAnnotated()) { Error(diagnostics, ErrorCode.ERR_AsNullableType, node.Right, targetType); return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } else if (!targetType.IsReferenceType && !targetType.IsNullableType()) { // SPEC: In an operation of the form E as T, E must be an expression and T must be a // SPEC: reference type, a type parameter known to be a reference type, or a nullable type. if (targetTypeKind == TypeKind.TypeParameter) { Error(diagnostics, ErrorCode.ERR_AsWithTypeVar, node, targetType); } else if (targetTypeKind == TypeKind.Pointer || targetTypeKind == TypeKind.FunctionPointer) { Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, node); } else { Error(diagnostics, ErrorCode.ERR_AsMustHaveReferenceType, node, targetType); } return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } // The C# specification states in the section called // "Referencing Static Class Types" that it is always // illegal to use "as" with a static type. The // native compiler actually allows "null as C" for // a static type C to be an expression of type C. // It also allows "someObject as C" if "someObject" // is of type object. To retain compatibility we // allow it, but when /warn:5 or higher we break with the native // compiler and turn this into a warning. if (targetType.IsStatic) { Error(diagnostics, ErrorCode.WRN_StaticInAsOrIs, node, targetType); } if (operand.IsLiteralNull()) { // We do not want to warn for the case "null as TYPE" where the null // is a literal, because the user might be saying it to cause overload resolution // to pick a particular method return new BoundAsOperator(node, operand, typeExpression, Conversion.NullLiteral, resultType); } if (operand.IsLiteralDefault()) { operand = new BoundDefaultExpression(operand.Syntax, targetType: null, constantValueOpt: ConstantValue.Null, type: GetSpecialType(SpecialType.System_Object, diagnostics, node)); } var operandType = operand.Type; Debug.Assert((object)operandType != null); var operandTypeKind = operandType.TypeKind; Debug.Assert(!targetType.IsPointerOrFunctionPointer(), "Should have been caught above"); if (operandType.IsPointerOrFunctionPointer()) { // operand for an is or as expression cannot be of pointer type Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, node); return new BoundAsOperator(node, operand, typeExpression, Conversion.NoConversion, resultType, hasErrors: true); } if (operandTypeKind == TypeKind.Dynamic) { // if operand has a dynamic type, we do the same thing as though it were an object operandType = GetSpecialType(SpecialType.System_Object, diagnostics, node); operandTypeKind = operandType.TypeKind; } if (targetTypeKind == TypeKind.Dynamic) { // for "as dynamic", we do the same thing as though it were an "as object" targetType = GetSpecialType(SpecialType.System_Object, diagnostics, node); targetTypeKind = targetType.TypeKind; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyBuiltInConversion(operandType, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); bool hasErrors = ReportAsOperatorConversionDiagnostics(node, diagnostics, this.Compilation, operandType, targetType, conversion.Kind, operand.ConstantValue); return new BoundAsOperator(node, operand, typeExpression, conversion, resultType, hasErrors); } private static bool ReportAsOperatorConversionDiagnostics( CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, CSharpCompilation compilation, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) { // SPEC: In an operation of the form E as T, E must be an expression and T must be a reference type, // SPEC: a type parameter known to be a reference type, or a nullable type. // SPEC: Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs: // SPEC: • An identity (§6.1.1), implicit nullable (§6.1.4), implicit reference (§6.1.6), boxing (§6.1.7), // SPEC: explicit nullable (§6.2.3), explicit reference (§6.2.4), or unboxing (§6.2.5) conversion exists // SPEC: from E to T. // SPEC: • The type of E or T is an open type. // SPEC: • E is the null literal. // SPEC VIOLATION: The specification contains an error in the list of legal conversions above. // SPEC VIOLATION: If we have "class C<T, U> where T : U where U : class" then there is // SPEC VIOLATION: an implicit conversion from T to U, but it is not an identity, reference or // SPEC VIOLATION: boxing conversion. It will be one of those at runtime, but at compile time // SPEC VIOLATION: we do not know which, and therefore cannot classify it as any of those. // SPEC VIOLATION: See Microsoft.CodeAnalysis.CSharp.UnitTests.SyntaxBinderTests.TestAsOperator_SpecErrorCase() test for an example. // SPEC VIOLATION: The specification also unintentionally allows the case where requirement 2 above: // SPEC VIOLATION: "The type of E or T is an open type" is true, but type of E is void type, i.e. T is an open type. // SPEC VIOLATION: Dev10 compiler correctly generates an error for this case and we will maintain compatibility. bool hasErrors = false; switch (conversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: case ConversionKind.Identity: case ConversionKind.ExplicitNullable: case ConversionKind.ExplicitReference: case ConversionKind.Unboxing: break; default: // Generate an error if there is no possible legal conversion and both the operandType // and the targetType are closed types OR operandType is void type, otherwise we need a runtime check if (!operandType.ContainsTypeParameter() && !targetType.ContainsTypeParameter() || operandType.IsVoidType()) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, operandType, targetType); Error(diagnostics, ErrorCode.ERR_NoExplicitBuiltinConv, node, distinguisher.First, distinguisher.Second); hasErrors = true; } break; } if (!hasErrors) { ReportAsOperatorConstantWarnings(node, diagnostics, operandType, targetType, conversionKind, operandConstantValue); } return hasErrors; } private static void ReportAsOperatorConstantWarnings( CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) { // NOTE: Even though BoundIsOperator and BoundAsOperator will always have no ConstantValue // NOTE: (they are non-constant expressions according to Section 7.19 of the specification), // NOTE: we want to perform constant analysis of is/as expressions to generate warnings if the // NOTE: expression will always be true/false/null. ConstantValue constantValue = GetAsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); if (constantValue != null) { Debug.Assert(constantValue.IsNull); Error(diagnostics, ErrorCode.WRN_AlwaysNull, node, targetType); } } internal static ConstantValue GetAsOperatorConstantResult(TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) { // NOTE: Even though BoundIsOperator and BoundAsOperator will always have no ConstantValue // NOTE: (they are non-constant expressions according to Section 7.19 of the specification), // NOTE: we want to perform constant analysis of is/as expressions during binding to generate warnings (always true/false/null) // NOTE: and during rewriting for optimized codegen. ConstantValue isOperatorConstantResult = GetIsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); if (isOperatorConstantResult != null && !isOperatorConstantResult.BooleanValue) { return ConstantValue.Null; } return null; } private BoundExpression GenerateNullCoalescingBadBinaryOpsError(BinaryExpressionSyntax node, BoundExpression leftOperand, BoundExpression rightOperand, Conversion leftConversion, BindingDiagnosticBag diagnostics) { Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, SyntaxFacts.GetText(node.OperatorToken.Kind()), leftOperand.Display, rightOperand.Display); leftOperand = BindToTypeForErrorRecovery(leftOperand); rightOperand = BindToTypeForErrorRecovery(rightOperand); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, leftConversion, BoundNullCoalescingOperatorResultKind.NoCommonType, CreateErrorType(), hasErrors: true); } private BoundExpression BindNullCoalescingOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { var leftOperand = BindValue(node.Left, diagnostics, BindValueKind.RValue); leftOperand = BindToNaturalType(leftOperand, diagnostics); var rightOperand = BindValue(node.Right, diagnostics, BindValueKind.RValue); // If either operand is bad, bail out preventing more cascading errors if (leftOperand.HasAnyErrors || rightOperand.HasAnyErrors) { leftOperand = BindToTypeForErrorRecovery(leftOperand); rightOperand = BindToTypeForErrorRecovery(rightOperand); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, Conversion.NoConversion, BoundNullCoalescingOperatorResultKind.NoCommonType, CreateErrorType(), hasErrors: true); } // The specification does not permit the left hand side to be a default literal if (leftOperand.IsLiteralDefault()) { Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, node.OperatorToken.Text, "default"); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, Conversion.NoConversion, BoundNullCoalescingOperatorResultKind.NoCommonType, CreateErrorType(), hasErrors: true); } // SPEC: The type of the expression a ?? b depends on which implicit conversions are available // SPEC: between the types of the operands. In order of preference, the type of a ?? b is A0, A, or B, // SPEC: where A is the type of a, B is the type of b (provided that b has a type), // SPEC: and A0 is the underlying type of A if A is a nullable type, or A otherwise. TypeSymbol optLeftType = leftOperand.Type; // "A" TypeSymbol optRightType = rightOperand.Type; // "B" bool isLeftNullable = (object)optLeftType != null && optLeftType.IsNullableType(); TypeSymbol optLeftType0 = isLeftNullable ? // "A0" optLeftType.GetNullableUnderlyingType() : optLeftType; // SPEC: The left hand side must be either the null literal or it must have a type. Lambdas and method groups do not have a type, // SPEC: so using one is an error. if (leftOperand.Kind == BoundKind.UnboundLambda || leftOperand.Kind == BoundKind.MethodGroup) { return GenerateNullCoalescingBadBinaryOpsError(node, leftOperand, rightOperand, Conversion.NoConversion, diagnostics); } // SPEC: Otherwise, if A exists and is a non-nullable value type, a compile-time error occurs. First we check for the pre-C# 8.0 // SPEC: condition, to ensure that we don't allow previously illegal code in old language versions. if ((object)optLeftType != null && !optLeftType.IsReferenceType && !isLeftNullable) { // Prior to C# 8.0, the spec said that the left type must be either a reference type or a nullable value type. This was relaxed // with C# 8.0, so if the feature is not enabled then issue a diagnostic and return if (!optLeftType.IsValueType) { CheckFeatureAvailability(node, MessageID.IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator, diagnostics); } else { return GenerateNullCoalescingBadBinaryOpsError(node, leftOperand, rightOperand, Conversion.NoConversion, diagnostics); } } // SPEC: If b is a dynamic expression, the result is dynamic. At runtime, a is first // SPEC: evaluated. If a is not null, a is converted to a dynamic type, and this becomes // SPEC: the result. Otherwise, b is evaluated, and the outcome becomes the result. // // Note that there is no runtime dynamic dispatch since comparison with null is not a dynamic operation. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if ((object)optRightType != null && optRightType.IsDynamic()) { var leftConversion = Conversions.ClassifyConversionFromExpression(leftOperand, GetSpecialType(SpecialType.System_Object, diagnostics, node), ref useSiteInfo); rightOperand = BindToNaturalType(rightOperand, diagnostics); diagnostics.Add(node, useSiteInfo); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, leftConversion, BoundNullCoalescingOperatorResultKind.RightDynamicType, optRightType); } // SPEC: Otherwise, if A exists and is a nullable type and an implicit conversion exists from b to A0, // SPEC: the result type is A0. At run-time, a is first evaluated. If a is not null, // SPEC: a is unwrapped to type A0, and this becomes the result. // SPEC: Otherwise, b is evaluated and converted to type A0, and this becomes the result. if (isLeftNullable) { var rightConversion = Conversions.ClassifyImplicitConversionFromExpression(rightOperand, optLeftType0, ref useSiteInfo); if (rightConversion.Exists) { var leftConversion = Conversions.ClassifyConversionFromExpression(leftOperand, optLeftType0, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); var convertedRightOperand = CreateConversion(rightOperand, rightConversion, optLeftType0, diagnostics); return new BoundNullCoalescingOperator(node, leftOperand, convertedRightOperand, leftConversion, BoundNullCoalescingOperatorResultKind.LeftUnwrappedType, optLeftType0); } } // SPEC: Otherwise, if A exists and an implicit conversion exists from b to A, the result type is A. // SPEC: At run-time, a is first evaluated. If a is not null, a becomes the result. // SPEC: Otherwise, b is evaluated and converted to type A, and this becomes the result. if ((object)optLeftType != null) { var rightConversion = Conversions.ClassifyImplicitConversionFromExpression(rightOperand, optLeftType, ref useSiteInfo); if (rightConversion.Exists) { var convertedRightOperand = CreateConversion(rightOperand, rightConversion, optLeftType, diagnostics); var leftConversion = Conversion.Identity; diagnostics.Add(node, useSiteInfo); return new BoundNullCoalescingOperator(node, leftOperand, convertedRightOperand, leftConversion, BoundNullCoalescingOperatorResultKind.LeftType, optLeftType); } } // SPEC: Otherwise, if b has a type B and an implicit conversion exists from a to B, // SPEC: the result type is B. At run-time, a is first evaluated. If a is not null, // SPEC: a is unwrapped to type A0 (if A exists and is nullable) and converted to type B, // SPEC: and this becomes the result. Otherwise, b is evaluated and becomes the result. // SPEC VIOLATION: Native compiler violates the specification here and implements this part based on // SPEC VIOLATION: whether A is a nullable type or not. // SPEC VIOLATION: We will maintain compatibility with the native compiler and do the same. // SPEC VIOLATION: Following SPEC PROPOSAL states the current implementations in both compilers: // SPEC PROPOSAL: Otherwise, if A exists and is a nullable type and if b has a type B and // SPEC PROPOSAL: an implicit conversion exists from A0 to B, the result type is B. // SPEC PROPOSAL: At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 // SPEC PROPOSAL: and converted to type B, and this becomes the result. // SPEC PROPOSAL: Otherwise, b is evaluated and becomes the result. // SPEC PROPOSAL: Otherwise, if A does not exist or is a non-nullable type and if b has a type B and // SPEC PROPOSAL: an implicit conversion exists from a to B, the result type is B. // SPEC PROPOSAL: At run-time, a is first evaluated. If a is not null, a is converted to type B, // SPEC PROPOSAL: and this becomes the result. Otherwise, b is evaluated and becomes the result. // See test CodeGenTests.TestNullCoalescingOperatorWithNullableConversions for an example. if ((object)optRightType != null) { rightOperand = BindToNaturalType(rightOperand, diagnostics); Conversion leftConversion; BoundNullCoalescingOperatorResultKind resultKind; if (isLeftNullable) { // This is the SPEC VIOLATION case. // Note that at runtime we need two conversions on the left operand: // 1) Explicit nullable conversion from leftOperand to optLeftType0 and // 2) Implicit conversion from optLeftType0 to optRightType. // We just store the second conversion in the bound node and insert the first conversion during rewriting // the null coalescing operator. See method LocalRewriter.GetConvertedLeftForNullCoalescingOperator. leftConversion = Conversions.ClassifyImplicitConversionFromType(optLeftType0, optRightType, ref useSiteInfo); resultKind = BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType; } else { leftConversion = Conversions.ClassifyImplicitConversionFromExpression(leftOperand, optRightType, ref useSiteInfo); resultKind = BoundNullCoalescingOperatorResultKind.RightType; } if (leftConversion.Exists) { if (!leftConversion.IsValid) { // CreateConversion here to generate diagnostics. if (isLeftNullable) { var conversion = Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, leftConversion); var strippedLeftOperand = CreateConversion(leftOperand, conversion, optLeftType0, diagnostics); leftOperand = CreateConversion(strippedLeftOperand, leftConversion, optRightType, diagnostics); } else { leftOperand = CreateConversion(leftOperand, leftConversion, optRightType, diagnostics); } Debug.Assert(leftOperand.HasAnyErrors); } else { ReportDiagnosticsIfObsolete(diagnostics, leftConversion, node, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(node, leftConversion, diagnostics); } diagnostics.Add(node, useSiteInfo); return new BoundNullCoalescingOperator(node, leftOperand, rightOperand, leftConversion, resultKind, optRightType); } } // SPEC: Otherwise, a and b are incompatible, and a compile-time error occurs. diagnostics.Add(node, useSiteInfo); return GenerateNullCoalescingBadBinaryOpsError(node, leftOperand, rightOperand, Conversion.NoConversion, diagnostics); } private BoundExpression BindNullCoalescingAssignmentOperator(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression leftOperand = BindValue(node.Left, diagnostics, BindValueKind.CompoundAssignment); ReportSuppressionIfNeeded(leftOperand, diagnostics); BoundExpression rightOperand = BindValue(node.Right, diagnostics, BindValueKind.RValue); // If either operand is bad, bail out preventing more cascading errors if (leftOperand.HasAnyErrors || rightOperand.HasAnyErrors) { leftOperand = BindToTypeForErrorRecovery(leftOperand); rightOperand = BindToTypeForErrorRecovery(rightOperand); return new BoundNullCoalescingAssignmentOperator(node, leftOperand, rightOperand, CreateErrorType(), hasErrors: true); } // Given a ??= b, the type of a is A, the type of B is b, and if A is a nullable value type, the underlying // non-nullable value type of A is A0. TypeSymbol leftType = leftOperand.Type; Debug.Assert((object)leftType != null); // If A is a non-nullable value type, a compile-time error occurs if (leftType.IsValueType && !leftType.IsNullableType()) { return GenerateNullCoalescingAssignmentBadBinaryOpsError(node, leftOperand, rightOperand, diagnostics); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // If A0 exists and B is implicitly convertible to A0, then the result type of this expression is A0, except if B is dynamic. // This differs from most assignments such that you cannot directly replace a with (a ??= b). // The exception for dynamic is called out in the spec, it's the same behavior that ?? has with respect to dynamic. if (leftType.IsNullableType()) { var underlyingLeftType = leftType.GetNullableUnderlyingType(); var underlyingRightConversion = Conversions.ClassifyImplicitConversionFromExpression(rightOperand, underlyingLeftType, ref useSiteInfo); if (underlyingRightConversion.Exists && rightOperand.Type?.IsDynamic() != true) { diagnostics.Add(node, useSiteInfo); var convertedRightOperand = CreateConversion(rightOperand, underlyingRightConversion, underlyingLeftType, diagnostics); return new BoundNullCoalescingAssignmentOperator(node, leftOperand, convertedRightOperand, underlyingLeftType); } } // If an implicit conversion exists from B to A, we store that conversion. At runtime, a is first evaluated. If // a is not null, b is not evaluated. If a is null, b is evaluated and converted to type A, and is stored in a. // Reset useSiteDiagnostics because they could have been used populated incorrectly from attempting to bind // as the nullable underlying value type case. useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); var rightConversion = Conversions.ClassifyImplicitConversionFromExpression(rightOperand, leftType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (rightConversion.Exists) { var convertedRightOperand = CreateConversion(rightOperand, rightConversion, leftType, diagnostics); return new BoundNullCoalescingAssignmentOperator(node, leftOperand, convertedRightOperand, leftType); } // a and b are incompatible and a compile-time error occurs return GenerateNullCoalescingAssignmentBadBinaryOpsError(node, leftOperand, rightOperand, diagnostics); } private BoundExpression GenerateNullCoalescingAssignmentBadBinaryOpsError(AssignmentExpressionSyntax node, BoundExpression leftOperand, BoundExpression rightOperand, BindingDiagnosticBag diagnostics) { Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, SyntaxFacts.GetText(node.OperatorToken.Kind()), leftOperand.Display, rightOperand.Display); leftOperand = BindToTypeForErrorRecovery(leftOperand); rightOperand = BindToTypeForErrorRecovery(rightOperand); return new BoundNullCoalescingAssignmentOperator(node, leftOperand, rightOperand, CreateErrorType(), hasErrors: true); } /// <remarks> /// From ExpressionBinder::EnsureQMarkTypesCompatible: /// /// The v2.0 specification states that the types of the second and third operands T and S of a conditional operator /// must be TT and TS such that either (a) TT==TS, or (b), TT->TS or TS->TT but not both. /// /// Unfortunately that is not what we implemented in v2.0. Instead, we implemented /// that either (a) TT=TS or (b) T->TS or S->TT but not both. That is, we looked at the /// convertibility of the expressions, not the types. /// /// /// Changing that to the algorithm in the standard would be a breaking change. /// /// b ? (Func&lt;int&gt;)(delegate(){return 1;}) : (delegate(){return 2;}) /// /// and /// /// b ? 0 : myenum /// /// would suddenly stop working. (The first because o2 has no type, the second because 0 goes to /// any enum but enum doesn't go to int.) /// /// It gets worse. We would like the 3.0 language features which require type inference to use /// a consistent algorithm, and that furthermore, the algorithm be smart about choosing the best /// of a set of types. However, the language committee has decided that this algorithm will NOT /// consume information about the convertibility of expressions. Rather, it will gather up all /// the possible types and then pick the "largest" of them. /// /// To maintain backwards compatibility while still participating in the spirit of consistency, /// we implement an algorithm here which picks the type based on expression convertibility, but /// if there is a conflict, then it chooses the larger type rather than producing a type error. /// This means that b?0:myshort will have type int rather than producing an error (because 0->short, /// myshort->int). /// </remarks> private BoundExpression BindConditionalOperator(ConditionalExpressionSyntax node, BindingDiagnosticBag diagnostics) { var whenTrue = node.WhenTrue.CheckAndUnwrapRefExpression(diagnostics, out var whenTrueRefKind); var whenFalse = node.WhenFalse.CheckAndUnwrapRefExpression(diagnostics, out var whenFalseRefKind); var isRef = whenTrueRefKind == RefKind.Ref && whenFalseRefKind == RefKind.Ref; if (!isRef) { if (whenFalseRefKind == RefKind.Ref) { diagnostics.Add(ErrorCode.ERR_RefConditionalNeedsTwoRefs, whenFalse.GetFirstToken().GetLocation()); } if (whenTrueRefKind == RefKind.Ref) { diagnostics.Add(ErrorCode.ERR_RefConditionalNeedsTwoRefs, whenTrue.GetFirstToken().GetLocation()); } } else { CheckFeatureAvailability(node, MessageID.IDS_FeatureRefConditional, diagnostics); } return isRef ? BindRefConditionalOperator(node, whenTrue, whenFalse, diagnostics) : BindValueConditionalOperator(node, whenTrue, whenFalse, diagnostics); } #nullable enable private BoundExpression BindValueConditionalOperator(ConditionalExpressionSyntax node, ExpressionSyntax whenTrue, ExpressionSyntax whenFalse, BindingDiagnosticBag diagnostics) { BoundExpression condition = BindBooleanExpression(node.Condition, diagnostics); BoundExpression trueExpr = BindValue(whenTrue, diagnostics, BindValueKind.RValue); BoundExpression falseExpr = BindValue(whenFalse, diagnostics, BindValueKind.RValue); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); ConstantValue? constantValue = null; TypeSymbol? bestType = BestTypeInferrer.InferBestTypeForConditionalOperator(trueExpr, falseExpr, this.Conversions, out bool hadMultipleCandidates, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (bestType is null) { ErrorCode noCommonTypeError = hadMultipleCandidates ? ErrorCode.ERR_AmbigQM : ErrorCode.ERR_InvalidQM; constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); return new BoundUnconvertedConditionalOperator(node, condition, trueExpr, falseExpr, constantValue, noCommonTypeError, type: null, hasErrors: constantValue?.IsBad == true); } TypeSymbol type; bool hasErrors; if (bestType.IsErrorType()) { trueExpr = BindToNaturalType(trueExpr, diagnostics, reportNoTargetType: false); falseExpr = BindToNaturalType(falseExpr, diagnostics, reportNoTargetType: false); type = bestType; hasErrors = true; } else { trueExpr = GenerateConversionForAssignment(bestType, trueExpr, diagnostics); falseExpr = GenerateConversionForAssignment(bestType, falseExpr, diagnostics); hasErrors = trueExpr.HasAnyErrors || falseExpr.HasAnyErrors; // If one of the conversions went wrong (e.g. return type of method group being converted // didn't match), then we don't want to use bestType because it's not accurate. type = hasErrors ? CreateErrorType() : bestType; } if (!hasErrors) { constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); hasErrors = constantValue != null && constantValue.IsBad; } return new BoundConditionalOperator(node, isRef: false, condition, trueExpr, falseExpr, constantValue, naturalTypeOpt: type, wasTargetTyped: false, type, hasErrors); } #nullable disable private BoundExpression BindRefConditionalOperator(ConditionalExpressionSyntax node, ExpressionSyntax whenTrue, ExpressionSyntax whenFalse, BindingDiagnosticBag diagnostics) { BoundExpression condition = BindBooleanExpression(node.Condition, diagnostics); BoundExpression trueExpr = BindValue(whenTrue, diagnostics, BindValueKind.RValue | BindValueKind.RefersToLocation); BoundExpression falseExpr = BindValue(whenFalse, diagnostics, BindValueKind.RValue | BindValueKind.RefersToLocation); bool hasErrors = trueExpr.HasErrors | falseExpr.HasErrors; TypeSymbol trueType = trueExpr.Type; TypeSymbol falseType = falseExpr.Type; TypeSymbol type; if (!Conversions.HasIdentityConversion(trueType, falseType)) { if (!hasErrors) diagnostics.Add(ErrorCode.ERR_RefConditionalDifferentTypes, falseExpr.Syntax.Location, trueType); type = CreateErrorType(); hasErrors = true; } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); type = BestTypeInferrer.InferBestTypeForConditionalOperator(trueExpr, falseExpr, this.Conversions, hadMultipleCandidates: out _, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); Debug.Assert(type is { }); Debug.Assert(Conversions.HasIdentityConversion(trueType, type)); Debug.Assert(Conversions.HasIdentityConversion(falseType, type)); } if (!hasErrors) { var currentScope = this.LocalScopeDepth; // val-escape must agree on both branches. uint whenTrueEscape = GetValEscape(trueExpr, currentScope); uint whenFalseEscape = GetValEscape(falseExpr, currentScope); if (whenTrueEscape != whenFalseEscape) { // ask the one with narrower escape, for the wider - hopefully the errors will make the violation easier to fix. if (whenTrueEscape < whenFalseEscape) CheckValEscape(falseExpr.Syntax, falseExpr, currentScope, whenTrueEscape, checkingReceiver: false, diagnostics: diagnostics); else CheckValEscape(trueExpr.Syntax, trueExpr, currentScope, whenFalseEscape, checkingReceiver: false, diagnostics: diagnostics); diagnostics.Add(ErrorCode.ERR_MismatchedRefEscapeInTernary, node.Location); hasErrors = true; } } trueExpr = BindToNaturalType(trueExpr, diagnostics, reportNoTargetType: false); falseExpr = BindToNaturalType(falseExpr, diagnostics, reportNoTargetType: false); return new BoundConditionalOperator(node, isRef: true, condition, trueExpr, falseExpr, constantValueOpt: null, type, wasTargetTyped: false, type, hasErrors); } /// <summary> /// Constant folding for conditional (aka ternary) operators. /// </summary> private static ConstantValue FoldConditionalOperator(BoundExpression condition, BoundExpression trueExpr, BoundExpression falseExpr) { ConstantValue trueValue = trueExpr.ConstantValue; if (trueValue == null || trueValue.IsBad) { return trueValue; } ConstantValue falseValue = falseExpr.ConstantValue; if (falseValue == null || falseValue.IsBad) { return falseValue; } ConstantValue conditionValue = condition.ConstantValue; if (conditionValue == null || conditionValue.IsBad) { return conditionValue; } else if (conditionValue == ConstantValue.True) { return trueValue; } else if (conditionValue == ConstantValue.False) { return falseValue; } else { return ConstantValue.Bad; } } private static void CheckNativeIntegerFeatureAvailability(BinaryOperatorKind operatorKind, SyntaxNode syntax, BindingDiagnosticBag diagnostics) { switch (operatorKind & BinaryOperatorKind.TypeMask) { case BinaryOperatorKind.NInt: case BinaryOperatorKind.NUInt: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureNativeInt, diagnostics); break; } } private static void CheckNativeIntegerFeatureAvailability(UnaryOperatorKind operatorKind, SyntaxNode syntax, BindingDiagnosticBag diagnostics) { switch (operatorKind & UnaryOperatorKind.TypeMask) { case UnaryOperatorKind.NInt: case UnaryOperatorKind.NUInt: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureNativeInt, diagnostics); break; } } } }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/BoundTree/BoundNodeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class BoundNodeExtensions { // Return if any node in an array of nodes has errors. public static bool HasErrors<T>(this ImmutableArray<T> nodeArray) where T : BoundNode { if (nodeArray.IsDefault) return false; for (int i = 0, n = nodeArray.Length; i < n; ++i) { if (nodeArray[i].HasErrors) return true; } return false; } // Like HasErrors property, but also returns false for a null node. public static bool HasErrors([NotNullWhen(true)] this BoundNode? node) { return node != null && node.HasErrors; } public static bool IsConstructorInitializer(this BoundStatement statement) { Debug.Assert(statement != null); if (statement!.Kind == BoundKind.ExpressionStatement) { BoundExpression expression = ((BoundExpressionStatement)statement).Expression; if (expression.Kind == BoundKind.Sequence && ((BoundSequence)expression).SideEffects.IsDefaultOrEmpty) { // in case there is a pattern variable declared in a ctor-initializer, it gets wrapped in a bound sequence. expression = ((BoundSequence)expression).Value; } return expression.Kind == BoundKind.Call && ((BoundCall)expression).IsConstructorInitializer(); } return false; } public static bool IsConstructorInitializer(this BoundCall call) { Debug.Assert(call != null); MethodSymbol method = call!.Method; BoundExpression? receiverOpt = call!.ReceiverOpt; return method.MethodKind == MethodKind.Constructor && receiverOpt != null && (receiverOpt.Kind == BoundKind.ThisReference || receiverOpt.Kind == BoundKind.BaseReference); } public static T MakeCompilerGenerated<T>(this T node) where T : BoundNode { node.WasCompilerGenerated = true; return node; } public static bool ContainsAwaitExpression(this ImmutableArray<BoundExpression> expressions) { var visitor = new ContainsAwaitVisitor(); foreach (var expression in expressions) { visitor.Visit(expression); if (visitor.ContainsAwait) { return true; } } return false; } private class ContainsAwaitVisitor : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { public bool ContainsAwait = false; public override BoundNode? Visit(BoundNode? node) => ContainsAwait ? null : base.Visit(node); public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { ContainsAwait = true; return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class BoundNodeExtensions { // Return if any node in an array of nodes has errors. public static bool HasErrors<T>(this ImmutableArray<T> nodeArray) where T : BoundNode { if (nodeArray.IsDefault) return false; for (int i = 0, n = nodeArray.Length; i < n; ++i) { if (nodeArray[i].HasErrors) return true; } return false; } // Like HasErrors property, but also returns false for a null node. public static bool HasErrors([NotNullWhen(true)] this BoundNode? node) { return node != null && node.HasErrors; } public static bool IsConstructorInitializer(this BoundStatement statement) { Debug.Assert(statement != null); if (statement!.Kind == BoundKind.ExpressionStatement) { BoundExpression expression = ((BoundExpressionStatement)statement).Expression; if (expression.Kind == BoundKind.Sequence && ((BoundSequence)expression).SideEffects.IsDefaultOrEmpty) { // in case there is a pattern variable declared in a ctor-initializer, it gets wrapped in a bound sequence. expression = ((BoundSequence)expression).Value; } return expression.Kind == BoundKind.Call && ((BoundCall)expression).IsConstructorInitializer(); } return false; } public static bool IsConstructorInitializer(this BoundCall call) { Debug.Assert(call != null); MethodSymbol method = call!.Method; BoundExpression? receiverOpt = call!.ReceiverOpt; return method.MethodKind == MethodKind.Constructor && receiverOpt != null && (receiverOpt.Kind == BoundKind.ThisReference || receiverOpt.Kind == BoundKind.BaseReference); } public static T MakeCompilerGenerated<T>(this T node) where T : BoundNode { node.WasCompilerGenerated = true; return node; } public static bool ContainsAwaitExpression(this ImmutableArray<BoundExpression> expressions) { var visitor = new ContainsAwaitVisitor(); foreach (var expression in expressions) { visitor.Visit(expression); if (visitor.ContainsAwait) { return true; } } return false; } private class ContainsAwaitVisitor : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { public bool ContainsAwait = false; public override BoundNode? Visit(BoundNode? node) => ContainsAwait ? null : base.Visit(node); public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { ContainsAwait = true; return null; } } /// <summary> /// Visits the binary operator tree of interpolated string additions in a depth-first pre-order visit, /// meaning parent, left, then right. /// <paramref name="stringCallback"/> controls whether to continue the visit by returning true or false: /// if true, the visit will continue. If false, the walk will be cut off. /// </summary> public static bool VisitBinaryOperatorInterpolatedString<TInterpolatedStringType, TArg>( this BoundBinaryOperator binary, TArg arg, Func<TInterpolatedStringType, TArg, bool> stringCallback, Action<BoundBinaryOperator, TArg>? binaryOperatorCallback = null) where TInterpolatedStringType : BoundInterpolatedStringBase { var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); pushLeftNodes(binary, stack, arg, binaryOperatorCallback); while (stack.TryPop(out BoundBinaryOperator? current)) { switch (current.Left) { case BoundBinaryOperator: break; case TInterpolatedStringType interpolatedString: if (!stringCallback(interpolatedString, arg)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(current.Left.Kind); } switch (current.Right) { case BoundBinaryOperator rightOperator: pushLeftNodes(rightOperator, stack, arg, binaryOperatorCallback); break; case TInterpolatedStringType interpolatedString: if (!stringCallback(interpolatedString, arg)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(current.Right.Kind); } } Debug.Assert(stack.Count == 0); stack.Free(); return true; static void pushLeftNodes(BoundBinaryOperator binary, ArrayBuilder<BoundBinaryOperator> stack, TArg arg, Action<BoundBinaryOperator, TArg>? binaryOperatorCallback) { Debug.Assert(typeof(TInterpolatedStringType) == typeof(BoundInterpolatedString) || binary.IsUnconvertedInterpolatedStringAddition); BoundBinaryOperator? current = binary; while (current != null) { binaryOperatorCallback?.Invoke(current, arg); stack.Push(current); current = current.Left as BoundBinaryOperator; } } } /// <summary> /// Rewrites a BoundBinaryOperator composed of interpolated strings (either converted or unconverted) iteratively, without /// recursion on the left side of the tree. Nodes of the tree are rewritten in a depth-first post-order fashion, meaning /// left, then right, then parent. /// </summary> /// <param name="binary">The original top of the binary operations.</param> /// <param name="arg">The callback args.</param> /// <param name="interpolatedStringFactory"> /// Rewriter for the BoundInterpolatedString or BoundUnconvertedInterpolatedString parts of the binary operator. Passed the callback /// parameter, the original interpolated string, and the index of the interpolated string in the tree. /// </param> /// <param name="binaryOperatorFactory"> /// Rewriter for the BoundBinaryOperator parts fo the binary operator. Passed the callback parameter, the original binary operator, and /// the rewritten left and right components. /// </param> public static TResult RewriteInterpolatedStringAddition<TInterpolatedStringType, TArg, TResult>( this BoundBinaryOperator binary, TArg arg, Func<TInterpolatedStringType, int, TArg, TResult> interpolatedStringFactory, Func<BoundBinaryOperator, TResult, TResult, TArg, TResult> binaryOperatorFactory) where TInterpolatedStringType : BoundInterpolatedStringBase { int i = 0; var result = doRewrite(binary, arg, interpolatedStringFactory, binaryOperatorFactory, ref i); return result; static TResult doRewrite( BoundBinaryOperator binary, TArg arg, Func<TInterpolatedStringType, int, TArg, TResult> interpolatedStringFactory, Func<BoundBinaryOperator, TResult, TResult, TArg, TResult> binaryOperatorFactory, ref int i) { TResult? result = default; var originalStack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); pushLeftNodes(binary, originalStack); while (originalStack.TryPop(out var currentBinary)) { Debug.Assert(currentBinary.Left is TInterpolatedStringType || result != null); TResult rewrittenLeft = currentBinary.Left switch { TInterpolatedStringType interpolatedString => interpolatedStringFactory(interpolatedString, i++, arg), BoundBinaryOperator => result!, _ => throw ExceptionUtilities.UnexpectedValue(currentBinary.Left.Kind) }; // For simplicity, we use recursion for binary operators on the right side of the tree. We're not traditionally concerned // with long chains of operators on the right side, as without parentheses we'll naturally make a tree that is deep on the // left side. If this ever changes, we can make this algorithm a more complex post-order iterative rewrite instead. var rewrittenRight = currentBinary.Right switch { TInterpolatedStringType interpolatedString => interpolatedStringFactory(interpolatedString, i++, arg), BoundBinaryOperator binaryOperator => doRewrite(binaryOperator, arg, interpolatedStringFactory, binaryOperatorFactory, ref i), _ => throw ExceptionUtilities.UnexpectedValue(currentBinary.Right.Kind) }; result = binaryOperatorFactory(currentBinary, rewrittenLeft, rewrittenRight, arg); } Debug.Assert(result != null); originalStack.Free(); return result; } static void pushLeftNodes(BoundBinaryOperator binary, ArrayBuilder<BoundBinaryOperator> stack) { BoundBinaryOperator? current = binary; while (current != null) { Debug.Assert(typeof(TInterpolatedStringType) == typeof(BoundInterpolatedString) || binary.IsUnconvertedInterpolatedStringAddition); stack.Push(current); current = current.Left as BoundBinaryOperator; } } } } }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// An abstract flow pass that takes some shortcuts in analyzing finally blocks, in order to enable /// the analysis to take place without tracking exceptions or repeating the analysis of a finally block /// for each exit from a try statement. The shortcut results in a slightly less precise /// (but still conservative) analysis, but that less precise analysis is all that is required for /// the language specification. The most significant shortcut is that we do not track the state /// where exceptions can arise. That does not affect the soundness for most analyses, but for those /// analyses whose soundness would be affected (e.g. "data flows out"), we track "unassignments" to keep /// the analysis sound. /// </summary> /// <remarks> /// Formally, this is a fairly conventional lattice flow analysis (<see /// href="https://en.wikipedia.org/wiki/Data-flow_analysis"/>) that moves upward through the <see cref="Join(ref /// TLocalState, ref TLocalState)"/> operation. /// </remarks> internal abstract partial class AbstractFlowPass<TLocalState, TLocalFunctionState> : BoundTreeVisitor where TLocalState : AbstractFlowPass<TLocalState, TLocalFunctionState>.ILocalState where TLocalFunctionState : AbstractFlowPass<TLocalState, TLocalFunctionState>.AbstractLocalFunctionState { protected int _recursionDepth; /// <summary> /// The compilation in which the analysis is taking place. This is needed to determine which /// conditional methods will be compiled and which will be omitted. /// </summary> protected readonly CSharpCompilation compilation; /// <summary> /// The method whose body is being analyzed, or the field whose initializer is being analyzed. /// May be a top-level member or a lambda or local function. It is used for /// references to method parameters. Thus, '_symbol' should not be used directly, but /// 'MethodParameters', 'MethodThisParameter' and 'AnalyzeOutParameters(...)' should be used /// instead. _symbol is null during speculative binding. /// </summary> protected readonly Symbol _symbol; /// <summary> /// Reflects the enclosing member, lambda or local function at the current location (in the bound tree). /// </summary> protected Symbol CurrentSymbol; /// <summary> /// The bound node of the method or initializer being analyzed. /// </summary> protected readonly BoundNode methodMainNode; /// <summary> /// The flow analysis state at each label, computed by calling <see cref="Join(ref /// TLocalState, ref TLocalState)"/> on the state from branches to that label with the state /// when we fall into the label. Entries are created when the label is encountered. One /// case deserves special attention: when the destination of the branch is a label earlier /// in the code, it is possible (though rarely occurs in practice) that we are changing the /// state at a label that we've already analyzed. In that case we run another pass of the /// analysis to allow those changes to propagate. This repeats until no further changes to /// the state of these labels occurs. This can result in quadratic performance in unlikely /// but possible code such as this: "int x; if (cond) goto l1; x = 3; l5: print x; l4: goto /// l5; l3: goto l4; l2: goto l3; l1: goto l2;" /// </summary> private readonly PooledDictionary<LabelSymbol, TLocalState> _labels; /// <summary> /// Set to true after an analysis scan if the analysis was incomplete due to state changing /// after it was used by another analysis component. In this case the caller scans again (until /// this is false). Since the analysis proceeds by monotonically changing the state computed /// at each label, this must terminate. /// </summary> protected bool stateChangedAfterUse; /// <summary> /// All of the labels seen so far in this forward scan of the body /// </summary> private PooledHashSet<BoundStatement> _labelsSeen; /// <summary> /// Pending escapes generated in the current scope (or more deeply nested scopes). When jump /// statements (goto, break, continue, return) are processed, they are placed in the /// pendingBranches buffer to be processed later by the code handling the destination /// statement. As a special case, the processing of try-finally statements might modify the /// contents of the pendingBranches buffer to take into account the behavior of /// "intervening" finally clauses. /// </summary> protected ArrayBuilder<PendingBranch> PendingBranches { get; private set; } /// <summary> /// The definite assignment and/or reachability state at the point currently being analyzed. /// </summary> protected TLocalState State; protected TLocalState StateWhenTrue; protected TLocalState StateWhenFalse; protected bool IsConditionalState; /// <summary> /// Indicates that the transfer function for a particular node (the function mapping the /// state before the node to the state after the node) is not monotonic, in the sense that /// it can change the state in either direction in the lattice. If the transfer function is /// monotonic, the transfer function can only change the state toward the <see /// cref="UnreachableState"/>. Reachability and definite assignment are monotonic, and /// permit a more efficient analysis. Region analysis and nullable analysis are not /// monotonic. This is just an optimization; we could treat all of them as nonmonotonic /// without much loss of performance. In fact, this only affects the analysis of (relatively /// rare) try statements, and is only a slight optimization. /// </summary> private readonly bool _nonMonotonicTransfer; protected void SetConditionalState((TLocalState whenTrue, TLocalState whenFalse) state) { SetConditionalState(state.whenTrue, state.whenFalse); } protected void SetConditionalState(TLocalState whenTrue, TLocalState whenFalse) { IsConditionalState = true; State = default(TLocalState); StateWhenTrue = whenTrue; StateWhenFalse = whenFalse; } protected void SetState(TLocalState newState) { Debug.Assert(newState != null); StateWhenTrue = StateWhenFalse = default(TLocalState); IsConditionalState = false; State = newState; } protected void Split() { if (!IsConditionalState) { SetConditionalState(State, State.Clone()); } } protected void Unsplit() { if (IsConditionalState) { Join(ref StateWhenTrue, ref StateWhenFalse); SetState(StateWhenTrue); } } /// <summary> /// Where all diagnostics are deposited. /// </summary> protected DiagnosticBag Diagnostics { get; } #region Region // For region analysis, we maintain some extra data. protected RegionPlace regionPlace; // tells whether we are currently analyzing code before, during, or after the region protected readonly BoundNode firstInRegion, lastInRegion; protected readonly bool TrackingRegions; /// <summary> /// A cache of the state at the backward branch point of each loop. This is not needed /// during normal flow analysis, but is needed for DataFlowsOut region analysis. /// </summary> private readonly Dictionary<BoundLoopStatement, TLocalState> _loopHeadState; #endregion Region protected AbstractFlowPass( CSharpCompilation compilation, Symbol symbol, BoundNode node, BoundNode firstInRegion = null, BoundNode lastInRegion = null, bool trackRegions = false, bool nonMonotonicTransferFunction = false) { Debug.Assert(node != null); if (firstInRegion != null && lastInRegion != null) { trackRegions = true; } if (trackRegions) { Debug.Assert(firstInRegion != null); Debug.Assert(lastInRegion != null); int startLocation = firstInRegion.Syntax.SpanStart; int endLocation = lastInRegion.Syntax.Span.End; int length = endLocation - startLocation; Debug.Assert(length >= 0, "last comes before first"); this.RegionSpan = new TextSpan(startLocation, length); } PendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); _labels = PooledDictionary<LabelSymbol, TLocalState>.GetInstance(); this.Diagnostics = DiagnosticBag.GetInstance(); this.compilation = compilation; _symbol = symbol; CurrentSymbol = symbol; this.methodMainNode = node; this.firstInRegion = firstInRegion; this.lastInRegion = lastInRegion; _loopHeadState = new Dictionary<BoundLoopStatement, TLocalState>(ReferenceEqualityComparer.Instance); TrackingRegions = trackRegions; _nonMonotonicTransfer = nonMonotonicTransferFunction; } protected abstract string Dump(TLocalState state); protected string Dump() { return IsConditionalState ? $"true: {Dump(this.StateWhenTrue)} false: {Dump(this.StateWhenFalse)}" : Dump(this.State); } #if DEBUG protected string DumpLabels() { StringBuilder result = new StringBuilder(); result.Append("Labels{"); bool first = true; foreach (var key in _labels.Keys) { if (!first) { result.Append(", "); } string name = key.Name; if (string.IsNullOrEmpty(name)) { name = "<Label>" + key.GetHashCode(); } result.Append(name).Append(": ").Append(this.Dump(_labels[key])); first = false; } result.Append("}"); return result.ToString(); } #endif private void EnterRegionIfNeeded(BoundNode node) { if (TrackingRegions && node == this.firstInRegion && this.regionPlace == RegionPlace.Before) { EnterRegion(); } } /// <summary> /// Subclasses may override EnterRegion to perform any actions at the entry to the region. /// </summary> protected virtual void EnterRegion() { Debug.Assert(this.regionPlace == RegionPlace.Before); this.regionPlace = RegionPlace.Inside; } private void LeaveRegionIfNeeded(BoundNode node) { if (TrackingRegions && node == this.lastInRegion && this.regionPlace == RegionPlace.Inside) { LeaveRegion(); } } /// <summary> /// Subclasses may override LeaveRegion to perform any action at the end of the region. /// </summary> protected virtual void LeaveRegion() { Debug.Assert(IsInside); this.regionPlace = RegionPlace.After; } protected readonly TextSpan RegionSpan; protected bool RegionContains(TextSpan span) { // TODO: There are no scenarios involving a zero-length span // currently. If the assert fails, add a corresponding test. Debug.Assert(span.Length > 0); if (span.Length == 0) { return RegionSpan.Contains(span.Start); } return RegionSpan.Contains(span); } protected bool IsInside { get { return regionPlace == RegionPlace.Inside; } } protected virtual void EnterParameters(ImmutableArray<ParameterSymbol> parameters) { foreach (var parameter in parameters) { EnterParameter(parameter); } } protected virtual void EnterParameter(ParameterSymbol parameter) { } protected virtual void LeaveParameters( ImmutableArray<ParameterSymbol> parameters, SyntaxNode syntax, Location location) { foreach (ParameterSymbol parameter in parameters) { LeaveParameter(parameter, syntax, location); } } protected virtual void LeaveParameter(ParameterSymbol parameter, SyntaxNode syntax, Location location) { } public override BoundNode Visit(BoundNode node) { return VisitAlways(node); } protected BoundNode VisitAlways(BoundNode node) { BoundNode result = null; // We scan even expressions, because we must process lambdas contained within them. if (node != null) { EnterRegionIfNeeded(node); VisitWithStackGuard(node); LeaveRegionIfNeeded(node); } return result; } [DebuggerStepThrough] private BoundNode VisitWithStackGuard(BoundNode node) { var expression = node as BoundExpression; if (expression != null) { return VisitExpressionWithStackGuard(ref _recursionDepth, expression); } return base.Visit(node); } [DebuggerStepThrough] protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)base.Visit(node); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return false; // just let the original exception bubble up. } /// <summary> /// A pending branch. These are created for a return, break, continue, goto statement, /// yield return, yield break, await expression, and await foreach/using. The idea is that /// we don't know if the branch will eventually reach its destination because of an /// intervening finally block that cannot complete normally. So we store them up and handle /// them as we complete processing each construct. At the end of a block, if there are any /// pending branches to a label in that block we process the branch. Otherwise we relay it /// up to the enclosing construct as a pending branch of the enclosing construct. /// </summary> internal class PendingBranch { public readonly BoundNode Branch; public bool IsConditionalState; public TLocalState State; public TLocalState StateWhenTrue; public TLocalState StateWhenFalse; public readonly LabelSymbol Label; public PendingBranch(BoundNode branch, TLocalState state, LabelSymbol label, bool isConditionalState = false, TLocalState stateWhenTrue = default, TLocalState stateWhenFalse = default) { this.Branch = branch; this.State = state.Clone(); this.IsConditionalState = isConditionalState; if (isConditionalState) { this.StateWhenTrue = stateWhenTrue.Clone(); this.StateWhenFalse = stateWhenFalse.Clone(); } this.Label = label; } } /// <summary> /// Perform a single pass of flow analysis. Note that after this pass, /// this.backwardBranchChanged indicates if a further pass is required. /// </summary> protected virtual ImmutableArray<PendingBranch> Scan(ref bool badRegion) { var oldPending = SavePending(); Visit(methodMainNode); this.Unsplit(); RestorePending(oldPending); if (TrackingRegions && regionPlace != RegionPlace.After) { badRegion = true; } ImmutableArray<PendingBranch> result = RemoveReturns(); return result; } protected ImmutableArray<PendingBranch> Analyze(ref bool badRegion, Optional<TLocalState> initialState = default) { ImmutableArray<PendingBranch> returns; do { // the entry point of a method is assumed reachable regionPlace = RegionPlace.Before; this.State = initialState.HasValue ? initialState.Value : TopState(); PendingBranches.Clear(); this.stateChangedAfterUse = false; this.Diagnostics.Clear(); returns = this.Scan(ref badRegion); } while (this.stateChangedAfterUse); return returns; } protected virtual void Free() { this.Diagnostics.Free(); PendingBranches.Free(); _labelsSeen.Free(); _labels.Free(); } /// <summary> /// If a method is currently being analyzed returns its parameters, returns an empty array /// otherwise. /// </summary> protected ImmutableArray<ParameterSymbol> MethodParameters { get { var method = _symbol as MethodSymbol; return (object)method == null ? ImmutableArray<ParameterSymbol>.Empty : method.Parameters; } } /// <summary> /// If a method is currently being analyzed returns its 'this' parameter, returns null /// otherwise. /// </summary> protected ParameterSymbol MethodThisParameter { get { ParameterSymbol thisParameter = null; (_symbol as MethodSymbol)?.TryGetThisParameter(out thisParameter); return thisParameter; } } /// <summary> /// Specifies whether or not method's out parameters should be analyzed. If there's more /// than one location in the method being analyzed, then the method is partial and we prefer /// to report an out parameter in partial method error. /// </summary> /// <param name="location">location to be used</param> /// <returns>true if the out parameters of the method should be analyzed</returns> protected bool ShouldAnalyzeOutParameters(out Location location) { var method = _symbol as MethodSymbol; if ((object)method == null || method.Locations.Length != 1) { location = null; return false; } else { location = method.Locations[0]; return true; } } /// <summary> /// Return the flow analysis state associated with a label. /// </summary> /// <param name="label"></param> /// <returns></returns> protected virtual TLocalState LabelState(LabelSymbol label) { TLocalState result; if (_labels.TryGetValue(label, out result)) { return result; } result = UnreachableState(); _labels.Add(label, result); return result; } /// <summary> /// Return to the caller the set of pending return statements. /// </summary> /// <returns></returns> protected virtual ImmutableArray<PendingBranch> RemoveReturns() { ImmutableArray<PendingBranch> result; result = PendingBranches.ToImmutable(); PendingBranches.Clear(); // The caller should have handled and cleared labelsSeen. Debug.Assert(_labelsSeen.Count == 0); return result; } /// <summary> /// Set the current state to one that indicates that it is unreachable. /// </summary> protected void SetUnreachable() { this.State = UnreachableState(); } protected void VisitLvalue(BoundExpression node) { EnterRegionIfNeeded(node); switch (node?.Kind) { case BoundKind.Parameter: VisitLvalueParameter((BoundParameter)node); break; case BoundKind.Local: VisitLvalue((BoundLocal)node); break; case BoundKind.ThisReference: case BoundKind.BaseReference: break; case BoundKind.PropertyAccess: var access = (BoundPropertyAccess)node; if (Binder.AccessingAutoPropertyFromConstructor(access, _symbol)) { var backingField = (access.PropertySymbol as SourcePropertySymbolBase)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(access.ReceiverOpt, backingField); break; } } goto default; case BoundKind.FieldAccess: { BoundFieldAccess node1 = (BoundFieldAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.FieldSymbol); break; } case BoundKind.EventAccess: { BoundEventAccess node1 = (BoundEventAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.EventSymbol.AssociatedField); break; } case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: ((BoundTupleExpression)node).VisitAllElements((x, self) => self.VisitLvalue(x), this); break; default: VisitRvalue(node); break; } LeaveRegionIfNeeded(node); } protected virtual void VisitLvalue(BoundLocal node) { } /// <summary> /// Visit a boolean condition expression. /// </summary> /// <param name="node"></param> protected void VisitCondition(BoundExpression node) { Visit(node); AdjustConditionalState(node); } private void AdjustConditionalState(BoundExpression node) { if (IsConstantTrue(node)) { Unsplit(); SetConditionalState(this.State, UnreachableState()); } else if (IsConstantFalse(node)) { Unsplit(); SetConditionalState(UnreachableState(), this.State); } else if ((object)node.Type == null || node.Type.SpecialType != SpecialType.System_Boolean) { // a dynamic type or a type with operator true/false Unsplit(); } Split(); } /// <summary> /// Visit a general expression, where we will only need to determine if variables are /// assigned (or not). That is, we will not be needing AssignedWhenTrue and /// AssignedWhenFalse. /// </summary> /// <param name="isKnownToBeAnLvalue">True when visiting an rvalue that will actually be used as an lvalue, /// for example a ref parameter when simulating a read of it, or an argument corresponding to an in parameter</param> protected virtual void VisitRvalue(BoundExpression node, bool isKnownToBeAnLvalue = false) { Visit(node); Unsplit(); } /// <summary> /// Visit a statement. /// </summary> [DebuggerHidden] protected virtual void VisitStatement(BoundStatement statement) { Visit(statement); Debug.Assert(!this.IsConditionalState); } protected static bool IsConstantTrue(BoundExpression node) { return node.ConstantValue == ConstantValue.True; } protected static bool IsConstantFalse(BoundExpression node) { return node.ConstantValue == ConstantValue.False; } protected static bool IsConstantNull(BoundExpression node) { return node.ConstantValue == ConstantValue.Null; } /// <summary> /// Called at the point in a loop where the backwards branch would go to. /// </summary> private void LoopHead(BoundLoopStatement node) { TLocalState previousState; if (_loopHeadState.TryGetValue(node, out previousState)) { Join(ref this.State, ref previousState); } _loopHeadState[node] = this.State.Clone(); } /// <summary> /// Called at the point in a loop where the backward branch is placed. /// </summary> private void LoopTail(BoundLoopStatement node) { var oldState = _loopHeadState[node]; if (Join(ref oldState, ref this.State)) { _loopHeadState[node] = oldState; this.stateChangedAfterUse = true; } } /// <summary> /// Used to resolve break statements in each statement form that has a break statement /// (loops, switch). /// </summary> private void ResolveBreaks(TLocalState breakState, LabelSymbol label) { var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { Join(ref breakState, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } SetState(breakState); } /// <summary> /// Used to resolve continue statements in each statement form that supports it. /// </summary> private void ResolveContinues(LabelSymbol continueLabel) { var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == continueLabel) { // Technically, nothing in the language specification depends on the state // at the continue label, so we could just discard them instead of merging // the states. In fact, we need not have added continue statements to the // pending jump queue in the first place if we were interested solely in the // flow analysis. However, region analysis (in support of extract method) // and other forms of more precise analysis // depend on continue statements appearing in the pending branch queue, so // we process them from the queue here. Join(ref this.State, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } } /// <summary> /// Subclasses override this if they want to take special actions on processing a goto /// statement, when both the jump and the label have been located. /// </summary> protected virtual void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement target) { target.AssertIsLabeledStatement(); } /// <summary> /// To handle a label, we resolve all branches to that label. Returns true if the state of /// the label changes as a result. /// </summary> /// <param name="label">Target label</param> /// <param name="target">Statement containing the target label</param> private bool ResolveBranches(LabelSymbol label, BoundStatement target) { target?.AssertIsLabeledStatementWithLabel(label); bool labelStateChanged = false; var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { ResolveBranch(pending, label, target, ref labelStateChanged); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } return labelStateChanged; } protected virtual void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged) { var state = LabelState(label); if (target != null) { NoteBranch(pending, pending.Branch, target); } var changed = Join(ref state, ref pending.State); if (changed) { labelStateChanged = true; _labels[label] = state; } } protected struct SavedPending { public readonly ArrayBuilder<PendingBranch> PendingBranches; public readonly PooledHashSet<BoundStatement> LabelsSeen; public SavedPending(ArrayBuilder<PendingBranch> pendingBranches, PooledHashSet<BoundStatement> labelsSeen) { this.PendingBranches = pendingBranches; this.LabelsSeen = labelsSeen; } } /// <summary> /// Since branches cannot branch into constructs, only out, we save the pending branches /// when visiting more nested constructs. When tracking exceptions, we store the current /// state as the exception state for the following code. /// </summary> protected SavedPending SavePending() { Debug.Assert(!this.IsConditionalState); var result = new SavedPending(PendingBranches, _labelsSeen); PendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); return result; } /// <summary> /// We use this when closing a block that may contain labels or branches /// - branches to new labels are resolved /// - new labels are removed (no longer can be reached) /// - unresolved pending branches are carried forward /// </summary> /// <param name="oldPending">The old pending branches, which are to be merged with the current ones</param> protected void RestorePending(SavedPending oldPending) { foreach (var node in _labelsSeen) { switch (node.Kind) { case BoundKind.LabeledStatement: { var label = (BoundLabeledStatement)node; stateChangedAfterUse |= ResolveBranches(label.Label, label); } break; case BoundKind.LabelStatement: { var label = (BoundLabelStatement)node; stateChangedAfterUse |= ResolveBranches(label.Label, label); } break; case BoundKind.SwitchSection: { var sec = (BoundSwitchSection)node; foreach (var label in sec.SwitchLabels) { stateChangedAfterUse |= ResolveBranches(label.Label, sec); } } break; default: // there are no other kinds of labels throw ExceptionUtilities.UnexpectedValue(node.Kind); } } oldPending.PendingBranches.AddRange(this.PendingBranches); PendingBranches.Free(); PendingBranches = oldPending.PendingBranches; // We only use SavePending/RestorePending when there could be no branch into the region between them. // So there is no need to save the labels seen between the calls. If there were such a need, we would // do "this.labelsSeen.UnionWith(oldPending.LabelsSeen);" instead of the following assignment _labelsSeen.Free(); _labelsSeen = oldPending.LabelsSeen; } #region visitors /// <summary> /// Since each language construct must be handled according to the rules of the language specification, /// the default visitor reports that the construct for the node is not implemented in the compiler. /// </summary> public override BoundNode DefaultVisit(BoundNode node) { Debug.Assert(false, $"Should Visit{node.Kind} be overridden in {this.GetType().Name}?"); Diagnostics.Add(ErrorCode.ERR_InternalError, node.Syntax.Location); return null; } public override BoundNode VisitAttribute(BoundAttribute node) { // No flow analysis is ever done in attributes (or their arguments). return null; } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { VisitRvalue(node.Expression); SetUnreachable(); return node; } public override BoundNode VisitPassByCopy(BoundPassByCopy node) { VisitRvalue(node.Expression); return node; } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { Debug.Assert(!IsConditionalState); bool negated = node.Pattern.IsNegated(out var pattern); Debug.Assert(negated == node.IsNegated); if (VisitPossibleConditionalAccess(node.Expression, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); SetConditionalState(patternMatchesNull(pattern) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } else if (IsConditionalState) { // Patterns which only match a single boolean value should propagate conditional state // for example, `(a != null && a.M(out x)) is true` should have the same conditional state as `(a != null && a.M(out x))`. if (isBoolTest(pattern) is bool value) { if (!value) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { // Patterns which match more than a single boolean value cannot propagate conditional state // for example, `(a != null && a.M(out x)) is bool b` should not have conditional state Unsplit(); } } VisitPattern(pattern); var reachableLabels = node.DecisionDag.ReachableLabels; if (!reachableLabels.Contains(node.WhenTrueLabel)) { SetState(this.StateWhenFalse); SetConditionalState(UnreachableState(), this.State); } else if (!reachableLabels.Contains(node.WhenFalseLabel)) { SetState(this.StateWhenTrue); SetConditionalState(this.State, UnreachableState()); } if (negated) { SetConditionalState(this.StateWhenFalse, this.StateWhenTrue); } return node; static bool patternMatchesNull(BoundPattern pattern) { switch (pattern) { case BoundTypePattern: case BoundRecursivePattern: case BoundITuplePattern: case BoundRelationalPattern: case BoundDeclarationPattern { IsVar: false }: case BoundConstantPattern { ConstantValue: { IsNull: false } }: return false; case BoundConstantPattern { ConstantValue: { IsNull: true } }: return true; case BoundNegatedPattern negated: return !patternMatchesNull(negated.Negated); case BoundBinaryPattern binary: if (binary.Disjunction) { // `a?.b(out x) is null or C` // pattern matches null if either subpattern matches null var leftNullTest = patternMatchesNull(binary.Left); return patternMatchesNull(binary.Left) || patternMatchesNull(binary.Right); } // `a?.b out x is not null and var c` // pattern matches null only if both subpatterns match null return patternMatchesNull(binary.Left) && patternMatchesNull(binary.Right); case BoundDeclarationPattern { IsVar: true }: case BoundDiscardPattern: return true; default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } // Returns `true` if the pattern only matches a `true` input. // Returns `false` if the pattern only matches a `false` input. // Otherwise, returns `null`. static bool? isBoolTest(BoundPattern pattern) { switch (pattern) { case BoundConstantPattern { ConstantValue: { IsBoolean: true, BooleanValue: var boolValue } }: return boolValue; case BoundNegatedPattern negated: return !isBoolTest(negated.Negated); case BoundBinaryPattern binary: if (binary.Disjunction) { // `(a != null && a.b(out x)) is true or true` matches `true` // `(a != null && a.b(out x)) is true or false` matches any boolean // both subpatterns must have the same bool test for the test to propagate out var leftNullTest = isBoolTest(binary.Left); return leftNullTest is null ? null : leftNullTest != isBoolTest(binary.Right) ? null : leftNullTest; } // `(a != null && a.b(out x)) is true and true` matches `true` // `(a != null && a.b(out x)) is true and var x` matches `true` // `(a != null && a.b(out x)) is true and false` never matches and is a compile error return isBoolTest(binary.Left) ?? isBoolTest(binary.Right); case BoundConstantPattern { ConstantValue: { IsBoolean: false } }: case BoundDiscardPattern: case BoundTypePattern: case BoundRecursivePattern: case BoundITuplePattern: case BoundRelationalPattern: case BoundDeclarationPattern: return null; default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } } public virtual void VisitPattern(BoundPattern pattern) { Split(); } public override BoundNode VisitConstantPattern(BoundConstantPattern node) { // All patterns are handled by VisitPattern throw ExceptionUtilities.Unreachable; } public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { return VisitTupleExpression(node); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { return VisitTupleExpression(node); } private BoundNode VisitTupleExpression(BoundTupleExpression node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), null); return null; } public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { VisitRvalue(node.Left); VisitRvalue(node.Right); return null; } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { VisitRvalue(node.Receiver); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { VisitRvalue(node.Receiver); return null; } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { VisitRvalue(node.Expression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } #nullable enable protected BoundNode? VisitInterpolatedStringBase(BoundInterpolatedStringBase node, InterpolatedStringHandlerData? data) { // If there can be any branching, then we need to treat the expressions // as optionally evaluated. Otherwise, we treat them as always evaluated (BoundExpression? construction, bool useBoolReturns, bool firstPartIsConditional) = data switch { null => (null, false, false), { } d => (d.Construction, d.UsesBoolReturns, d.HasTrailingHandlerValidityParameter) }; VisitRvalue(construction); bool hasConditionalEvaluation = useBoolReturns || firstPartIsConditional; TLocalState? shortCircuitState = hasConditionalEvaluation ? State.Clone() : default; _ = VisitInterpolatedStringHandlerParts(node, useBoolReturns, firstPartIsConditional, ref shortCircuitState); if (hasConditionalEvaluation) { Debug.Assert(shortCircuitState != null); Join(ref this.State, ref shortCircuitState); } return null; } #nullable disable public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { return VisitInterpolatedStringBase(node, node.InterpolationData); } public override BoundNode VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // If the node is unconverted, we'll just treat it as if the contents are always evaluated return VisitInterpolatedStringBase(node, data: null); } public override BoundNode VisitStringInsert(BoundStringInsert node) { VisitRvalue(node.Value); if (node.Alignment != null) { VisitRvalue(node.Alignment); } if (node.Format != null) { VisitRvalue(node.Format); } return null; } public override BoundNode VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { return null; } public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { return null; } public override BoundNode VisitArgList(BoundArgList node) { // The "__arglist" expression that is legal inside a varargs method has no // effect on flow analysis and it has no children. return null; } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { // When we have M(__arglist(x, y, z)) we must visit x, y and z. VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { // Note that we require that the variable whose reference we are taking // has been initialized; it is similar to passing the variable as a ref parameter. VisitRvalue(node.Operand, isKnownToBeAnLvalue: true); return null; } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) { VisitStatement(node.Statement); return null; } public override BoundNode VisitLambda(BoundLambda node) => null; public override BoundNode VisitLocal(BoundLocal node) { SplitIfBooleanConstant(node); return null; } public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node) { if (node.InitializerOpt != null) { // analyze the expression VisitRvalue(node.InitializerOpt, isKnownToBeAnLvalue: node.LocalSymbol.RefKind != RefKind.None); // byref assignment is also a potential write if (node.LocalSymbol.RefKind != RefKind.None) { WriteArgument(node.InitializerOpt, node.LocalSymbol.RefKind, method: null); } } return null; } public override BoundNode VisitBlock(BoundBlock node) { VisitStatements(node.Statements); return null; } private void VisitStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { VisitStatement(statement); } } public override BoundNode VisitScope(BoundScope node) { VisitStatements(node.Statements); return null; } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitCall(BoundCall node) { // If the method being called is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // definite assignment analysis. bool callsAreOmitted = node.Method.CallsAreOmitted(node.SyntaxTree); TLocalState savedState = default(TLocalState); if (callsAreOmitted) { savedState = this.State.Clone(); SetUnreachable(); } VisitReceiverBeforeCall(node.ReceiverOpt, node.Method); VisitArgumentsBeforeCall(node.Arguments, node.ArgumentRefKindsOpt); if (node.Method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: true); } VisitArgumentsAfterCall(node.Arguments, node.ArgumentRefKindsOpt, node.Method); VisitReceiverAfterCall(node.ReceiverOpt, node.Method); if (callsAreOmitted) { this.State = savedState; } return null; } protected void VisitLocalFunctionUse(LocalFunctionSymbol symbol, SyntaxNode syntax, bool isCall) { var localFuncState = GetOrCreateLocalFuncUsages(symbol); VisitLocalFunctionUse(symbol, localFuncState, syntax, isCall); } protected virtual void VisitLocalFunctionUse( LocalFunctionSymbol symbol, TLocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { if (isCall) { Join(ref State, ref localFunctionState.StateFromBottom); Meet(ref State, ref localFunctionState.StateFromTop); } localFunctionState.Visited = true; } private void VisitReceiverBeforeCall(BoundExpression receiverOpt, MethodSymbol method) { if (method is null || method.MethodKind != MethodKind.Constructor) { VisitRvalue(receiverOpt); } } private void VisitReceiverAfterCall(BoundExpression receiverOpt, MethodSymbol method) { if (receiverOpt is null) { return; } if (method is null) { WriteArgument(receiverOpt, RefKind.Ref, method: null); } else if (method.TryGetThisParameter(out var thisParameter) && thisParameter is object && !TypeIsImmutable(thisParameter.Type)) { var thisRefKind = thisParameter.RefKind; if (thisRefKind.IsWritableReference()) { WriteArgument(receiverOpt, thisRefKind, method); } } } /// <summary> /// Certain (struct) types are known by the compiler to be immutable. In these cases calling a method on /// the type is known (by flow analysis) not to write the receiver. /// </summary> /// <param name="t"></param> /// <returns></returns> private static bool TypeIsImmutable(TypeSymbol t) { switch (t.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_DateTime: return true; default: return t.IsNullableType(); } } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { var method = GetReadMethod(node.Indexer); VisitReceiverBeforeCall(node.ReceiverOpt, method); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); if ((object)method != null) { VisitReceiverAfterCall(node.ReceiverOpt, method); } return null; } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { // Index or Range pattern indexers evaluate the following in order: // 1. The receiver // 1. The Count or Length method off the receiver // 2. The argument to the access // 3. The pattern method VisitRvalue(node.Receiver); var method = GetReadMethod(node.LengthOrCountProperty); VisitReceiverAfterCall(node.Receiver, method); VisitRvalue(node.Argument); method = node.PatternSymbol switch { PropertySymbol p => GetReadMethod(p), MethodSymbol m => m, _ => throw ExceptionUtilities.UnexpectedValue(node.PatternSymbol) }; VisitReceiverAfterCall(node.Receiver, method); return null; } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { VisitRvalue(node.ReceiverOpt); VisitRvalue(node.Argument); return null; } /// <summary> /// Do not call for a local function. /// </summary> protected virtual void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { Debug.Assert(method?.OriginalDefinition.MethodKind != MethodKind.LocalFunction); VisitArgumentsBeforeCall(arguments, refKindsOpt); VisitArgumentsAfterCall(arguments, refKindsOpt, method); } private void VisitArgumentsBeforeCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { // first value and ref parameters are read... for (int i = 0; i < arguments.Length; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); if (refKind != RefKind.Out) { VisitRvalue(arguments[i], isKnownToBeAnLvalue: refKind != RefKind.None); } else { VisitLvalue(arguments[i]); } } } /// <summary> /// Writes ref and out parameters /// </summary> private void VisitArgumentsAfterCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { for (int i = 0; i < arguments.Length; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); // passing as a byref argument is also a potential write if (refKind != RefKind.None) { WriteArgument(arguments[i], refKind, method); } } } protected static RefKind GetRefKind(ImmutableArray<RefKind> refKindsOpt, int index) { return refKindsOpt.IsDefault || refKindsOpt.Length <= index ? RefKind.None : refKindsOpt[index]; } protected virtual void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method) { } public override BoundNode VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { VisitRvalue(child as BoundExpression); } return null; } public override BoundNode VisitBadStatement(BoundBadStatement node) { foreach (var child in node.ChildBoundNodes) { if (child is BoundStatement) { VisitStatement(child as BoundStatement); } else { VisitRvalue(child as BoundExpression); } } return null; } // Can be called as part of a bad expression. public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) { foreach (var child in node.Initializers) { VisitRvalue(child); } return null; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { var methodGroup = node.Argument as BoundMethodGroup; if (methodGroup != null) { if ((object)node.MethodOpt != null && node.MethodOpt.RequiresInstanceReceiver) { EnterRegionIfNeeded(methodGroup); VisitRvalue(methodGroup.ReceiverOpt); LeaveRegionIfNeeded(methodGroup); } else if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false); } } else { VisitRvalue(node.Argument); } return null; } public override BoundNode VisitTypeExpression(BoundTypeExpression node) { return null; } public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // If we're seeing a node of this kind, then we failed to resolve the member access // as either a type or a property/field/event/local/parameter. In such cases, // the second interpretation applies so just visit the node for that. return this.Visit(node.Data.ValueExpression); } public override BoundNode VisitLiteral(BoundLiteral node) { SplitIfBooleanConstant(node); return null; } protected void SplitIfBooleanConstant(BoundExpression node) { if (node.ConstantValue is { IsBoolean: true, BooleanValue: bool booleanValue }) { var unreachable = UnreachableState(); Split(); if (booleanValue) { StateWhenFalse = unreachable; } else { StateWhenTrue = unreachable; } } } public override BoundNode VisitMethodDefIndex(BoundMethodDefIndex node) { return null; } public override BoundNode VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) { return null; } public override BoundNode VisitModuleVersionId(BoundModuleVersionId node) { return null; } public override BoundNode VisitModuleVersionIdString(BoundModuleVersionIdString node) { return null; } public override BoundNode VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) { return null; } public override BoundNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node) { return null; } public override BoundNode VisitConversion(BoundConversion node) { if (node.ConversionKind == ConversionKind.MethodGroup) { if (node.IsExtensionMethod || ((object)node.SymbolOpt != null && node.SymbolOpt.RequiresInstanceReceiver)) { BoundExpression receiver = ((BoundMethodGroup)node.Operand).ReceiverOpt; // A method group's "implicit this" is only used for instance methods. EnterRegionIfNeeded(node.Operand); VisitRvalue(receiver); LeaveRegionIfNeeded(node.Operand); } else if (node.SymbolOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false); } } else { Visit(node.Operand); } return null; } public override BoundNode VisitIfStatement(BoundIfStatement node) { // 5.3.3.5 If statements VisitCondition(node.Condition); TLocalState trueState = StateWhenTrue; TLocalState falseState = StateWhenFalse; SetState(trueState); VisitStatement(node.Consequence); trueState = this.State; SetState(falseState); if (node.AlternativeOpt != null) { VisitStatement(node.AlternativeOpt); } Join(ref this.State, ref trueState); return null; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var oldPending = SavePending(); // we do not allow branches into a try statement var initialState = this.State.Clone(); // use this state to resolve all the branches introduced and internal to try/catch var pendingBeforeTry = SavePending(); VisitTryBlockWithAnyTransferFunction(node.TryBlock, node, ref initialState); var finallyState = initialState.Clone(); var endState = this.State; foreach (var catchBlock in node.CatchBlocks) { SetState(initialState.Clone()); VisitCatchBlockWithAnyTransferFunction(catchBlock, ref finallyState); Join(ref endState, ref this.State); } // Give a chance to branches internal to try/catch to resolve. // Carry forward unresolved branches. RestorePending(pendingBeforeTry); // NOTE: At this point all branches that are internal to try or catch blocks have been resolved. // However we have not yet restored the oldPending branches. Therefore all the branches // that are currently pending must have been introduced in try/catch and do not terminate inside those blocks. // // With exception of YieldReturn, these branches logically go through finally, if such present, // so we must Union/Intersect finally state as appropriate if (node.FinallyBlockOpt != null) { // branches from the finally block, while illegal, should still not be considered // to execute the finally block before occurring. Also, we do not handle branches // *into* the finally block. SetState(finallyState); // capture tryAndCatchPending before going into finally // we will need pending branches as they were before finally later var tryAndCatchPending = SavePending(); var stateMovedUpInFinally = ReachableBottomState(); VisitFinallyBlockWithAnyTransferFunction(node.FinallyBlockOpt, ref stateMovedUpInFinally); foreach (var pend in tryAndCatchPending.PendingBranches) { if (pend.Branch == null) { continue; // a tracked exception } if (pend.Branch.Kind != BoundKind.YieldReturnStatement) { updatePendingBranchState(ref pend.State, ref stateMovedUpInFinally); if (pend.IsConditionalState) { updatePendingBranchState(ref pend.StateWhenTrue, ref stateMovedUpInFinally); updatePendingBranchState(ref pend.StateWhenFalse, ref stateMovedUpInFinally); } } } RestorePending(tryAndCatchPending); Meet(ref endState, ref this.State); if (_nonMonotonicTransfer) { Join(ref endState, ref stateMovedUpInFinally); } } SetState(endState); RestorePending(oldPending); return null; void updatePendingBranchState(ref TLocalState stateToUpdate, ref TLocalState stateMovedUpInFinally) { Meet(ref stateToUpdate, ref this.State); if (_nonMonotonicTransfer) { Join(ref stateToUpdate, ref stateMovedUpInFinally); } } } protected Optional<TLocalState> NonMonotonicState; /// <summary> /// Join state from other try block, potentially in a nested method. /// </summary> protected virtual void JoinTryBlockState(ref TLocalState self, ref TLocalState other) { Join(ref self, ref other); } private void VisitTryBlockWithAnyTransferFunction(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitTryBlock(tryBlock, node, ref tryState); var tempTryStateValue = NonMonotonicState.Value; Join(ref tryState, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitTryBlock(tryBlock, node, ref tryState); } } protected virtual void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) { VisitStatement(tryBlock); } private void VisitCatchBlockWithAnyTransferFunction(BoundCatchBlock catchBlock, ref TLocalState finallyState) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitCatchBlock(catchBlock, ref finallyState); var tempTryStateValue = NonMonotonicState.Value; Join(ref finallyState, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitCatchBlock(catchBlock, ref finallyState); } } protected virtual void VisitCatchBlock(BoundCatchBlock catchBlock, ref TLocalState finallyState) { if (catchBlock.ExceptionSourceOpt != null) { VisitLvalue(catchBlock.ExceptionSourceOpt); } if (catchBlock.ExceptionFilterPrologueOpt is { }) { VisitStatementList(catchBlock.ExceptionFilterPrologueOpt); } if (catchBlock.ExceptionFilterOpt != null) { VisitCondition(catchBlock.ExceptionFilterOpt); SetState(StateWhenTrue); } VisitStatement(catchBlock.Body); } private void VisitFinallyBlockWithAnyTransferFunction(BoundStatement finallyBlock, ref TLocalState stateMovedUp) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitFinallyBlock(finallyBlock, ref stateMovedUp); var tempTryStateValue = NonMonotonicState.Value; Join(ref stateMovedUp, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitFinallyBlock(finallyBlock, ref stateMovedUp); } } protected virtual void VisitFinallyBlock(BoundStatement finallyBlock, ref TLocalState stateMovedUp) { VisitStatement(finallyBlock); // this should generate no pending branches } public override BoundNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node) { return VisitBlock(node.FinallyBlock); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { var result = VisitReturnStatementNoAdjust(node); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return result; } protected virtual BoundNode VisitReturnStatementNoAdjust(BoundReturnStatement node) { VisitRvalue(node.ExpressionOpt, isKnownToBeAnLvalue: node.RefKind != RefKind.None); // byref return is also a potential write if (node.RefKind != RefKind.None) { WriteArgument(node.ExpressionOpt, node.RefKind, method: null); } return null; } public override BoundNode VisitThisReference(BoundThisReference node) { return null; } public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { return null; } public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { return null; } public override BoundNode VisitParameter(BoundParameter node) { return null; } protected virtual void VisitLvalueParameter(BoundParameter node) { } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Constructor); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNewT(BoundNewT node) { VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { VisitRvalue(node.InitializerExpressionOpt); return null; } // represents anything that occurs at the invocation of the property setter protected virtual void PropertySetter(BoundExpression node, BoundExpression receiver, MethodSymbol setter, BoundExpression value = null) { VisitReceiverAfterCall(receiver, setter); } // returns false if expression is not a property access // or if the property has a backing field // and accessed in a corresponding constructor private bool RegularPropertyAccess(BoundExpression expr) { if (expr.Kind != BoundKind.PropertyAccess) { return false; } return !Binder.AccessingAutoPropertyFromConstructor((BoundPropertyAccess)expr, _symbol); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var method = GetWriteMethod(property); VisitReceiverBeforeCall(left.ReceiverOpt, method); VisitRvalue(node.Right); PropertySetter(node, left.ReceiverOpt, method, node.Right); return null; } } VisitLvalue(node.Left); VisitRvalue(node.Right, isKnownToBeAnLvalue: node.IsRef); // byref assignment is also a potential write if (node.IsRef) { // Assume that BadExpression is a ref location to avoid // cascading diagnostics var refKind = node.Left.Kind == BoundKind.BadExpression ? RefKind.Ref : node.Left.GetRefKind(); WriteArgument(node.Right, refKind, method: null); } return null; } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { VisitLvalue(node.Left); VisitRvalue(node.Right); return null; } public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) { // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { VisitCompoundAssignmentTarget(node); VisitRvalue(node.Right); AfterRightHasBeenVisited(node); return null; } protected void VisitCompoundAssignmentTarget(BoundCompoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var readMethod = GetReadMethod(property); Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)GetWriteMethod(property)); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); return; } } VisitRvalue(node.Left, isKnownToBeAnLvalue: true); } protected void AfterRightHasBeenVisited(BoundCompoundAssignmentOperator node) { if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var writeMethod = GetWriteMethod(property); PropertySetter(node, left.ReceiverOpt, writeMethod); VisitReceiverAfterCall(left.ReceiverOpt, writeMethod); return; } } } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); return null; } private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol) { bool asLvalue = (object)fieldSymbol != null && (fieldSymbol.IsFixedSizeBuffer || !fieldSymbol.IsStatic && fieldSymbol.ContainingType.TypeKind == TypeKind.Struct && receiverOpt != null && receiverOpt.Kind != BoundKind.TypeExpression && (object)receiverOpt.Type != null && !receiverOpt.Type.IsPrimitiveRecursiveStruct()); if (asLvalue) { VisitLvalue(receiverOpt); } else { VisitRvalue(receiverOpt); } } public override BoundNode VisitFieldInfo(BoundFieldInfo node) { return null; } public override BoundNode VisitMethodInfo(BoundMethodInfo node) { return null; } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; if (Binder.AccessingAutoPropertyFromConstructor(node, _symbol)) { var backingField = (property as SourcePropertySymbolBase)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(node.ReceiverOpt, backingField); return null; } } var method = GetReadMethod(property); VisitReceiverBeforeCall(node.ReceiverOpt, method); VisitReceiverAfterCall(node.ReceiverOpt, method); return null; // TODO: In an expression such as // M().Prop = G(); // Exceptions thrown from M() occur before those from G(), but exceptions from the property accessor // occur after both. The precise abstract flow pass does not yet currently have this quite right. // Probably what is needed is a VisitPropertyAccessInternal(BoundPropertyAccess node, bool read) // which should assume that the receiver will have been handled by the caller. This can be invoked // twice for read/write operations such as // M().Prop += 1 // or at the appropriate place in the sequence for read or write operations. // Do events require any special handling too? } public override BoundNode VisitEventAccess(BoundEventAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.EventSymbol.AssociatedField); return null; } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return null; } public override BoundNode VisitQueryClause(BoundQueryClause node) { VisitRvalue(node.UnoptimizedForm ?? node.Value); return null; } private BoundNode VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) { foreach (var v in node.LocalDeclarations) { Visit(v); } return null; } public override BoundNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode VisitWhileStatement(BoundWhileStatement node) { // while (node.Condition) { node.Body; node.ContinueLabel: } node.BreakLabel: LoopHead(node); VisitCondition(node.Condition); TLocalState bodyState = StateWhenTrue; TLocalState breakState = StateWhenFalse; SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitWithExpression(BoundWithExpression node) { VisitRvalue(node.Receiver); VisitObjectOrCollectionInitializerExpression(node.InitializerExpression.Initializers); return null; } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { VisitRvalue(node.Expression); foreach (var i in node.Indices) { VisitRvalue(i); } return null; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { if (node.OperatorKind.IsLogical()) { Debug.Assert(!node.OperatorKind.IsUserDefined()); VisitBinaryLogicalOperatorChildren(node); } else if (node.InterpolatedStringHandlerData is { } data) { VisitBinaryInterpolatedStringAddition(node); } else { VisitBinaryOperatorChildren(node); } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { VisitBinaryLogicalOperatorChildren(node); return null; } private void VisitBinaryLogicalOperatorChildren(BoundExpression node) { // Do not blow the stack due to a deep recursion on the left. var stack = ArrayBuilder<BoundExpression>.GetInstance(); BoundExpression binary; BoundExpression child = node; while (true) { var childKind = child.Kind; if (childKind == BoundKind.BinaryOperator) { var binOp = (BoundBinaryOperator)child; if (!binOp.OperatorKind.IsLogical()) { break; } Debug.Assert(!binOp.OperatorKind.IsUserDefined()); binary = child; child = binOp.Left; } else if (childKind == BoundKind.UserDefinedConditionalLogicalOperator) { binary = child; child = ((BoundUserDefinedConditionalLogicalOperator)binary).Left; } else { break; } stack.Push(binary); } Debug.Assert(stack.Count > 0); VisitCondition(child); while (true) { binary = stack.Pop(); BinaryOperatorKind kind; BoundExpression right; switch (binary.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)binary; kind = binOp.OperatorKind; right = binOp.Right; break; case BoundKind.UserDefinedConditionalLogicalOperator: var udBinOp = (BoundUserDefinedConditionalLogicalOperator)binary; kind = udBinOp.OperatorKind; right = udBinOp.Right; break; default: throw ExceptionUtilities.UnexpectedValue(binary.Kind); } var op = kind.Operator(); var isAnd = op == BinaryOperatorKind.And; var isBool = kind.OperandTypes() == BinaryOperatorKind.Bool; Debug.Assert(isAnd || op == BinaryOperatorKind.Or); var leftTrue = this.StateWhenTrue; var leftFalse = this.StateWhenFalse; SetState(isAnd ? leftTrue : leftFalse); AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse); if (stack.Count == 0) { break; } AdjustConditionalState(binary); } Debug.Assert((object)binary == node); stack.Free(); } protected virtual void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) { Visit(right); // First part of VisitCondition AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse); } protected void AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) { AdjustConditionalState(right); // Second part of VisitCondition if (!isBool) { this.Unsplit(); this.Split(); } var resultTrue = this.StateWhenTrue; var resultFalse = this.StateWhenFalse; if (isAnd) { Join(ref resultFalse, ref leftFalse); } else { Join(ref resultTrue, ref leftTrue); } SetConditionalState(resultTrue, resultFalse); if (!isBool) { this.Unsplit(); } } private void VisitBinaryOperatorChildren(BoundBinaryOperator node) { // It is common in machine-generated code for there to be deep recursion on the left side of a binary // operator, for example, if you have "a + b + c + ... " then the bound tree will be deep on the left // hand side. To mitigate the risk of stack overflow we use an explicit stack. // // Of course we must ensure that we visit the left hand side before the right hand side. var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); BoundBinaryOperator binary = node; do { stack.Push(binary); binary = binary.Left as BoundBinaryOperator; } while (binary != null && !binary.OperatorKind.IsLogical() && binary.InterpolatedStringHandlerData is null); VisitBinaryOperatorChildren(stack); stack.Free(); } #nullable enable protected virtual void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(binary.Left, out var stateWhenNotNull) && canLearnFromOperator(binary) && isKnownNullOrNotNull(binary.Right)) { if (_nonMonotonicTransfer) { // In this very specific scenario, we need to do extra work to track unassignments for region analysis. // See `AbstractFlowPass.VisitCatchBlockWithAnyTransferFunction` for a similar scenario in catch blocks. Optional<TLocalState> oldState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitRvalue(binary.Right); var tempStateValue = NonMonotonicState.Value; Join(ref stateWhenNotNull, ref tempStateValue); if (oldState.HasValue) { var oldStateValue = oldState.Value; Join(ref oldStateValue, ref tempStateValue); oldState = oldStateValue; } NonMonotonicState = oldState; } else { VisitRvalue(binary.Right); Meet(ref stateWhenNotNull, ref State); } var isNullConstant = binary.Right.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); if (stack.Count == 0) { return; } binary = stack.Pop(); } while (true) { if (!canLearnFromOperator(binary) || !learnFromOperator(binary)) { Unsplit(); VisitRvalue(binary.Right); } if (stack.Count == 0) { break; } binary = stack.Pop(); } static bool canLearnFromOperator(BoundBinaryOperator binary) { var kind = binary.OperatorKind; return kind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual && (!kind.IsUserDefined() || kind.IsLifted()); } static bool isKnownNullOrNotNull(BoundExpression expr) { return expr.ConstantValue is object || (expr is BoundConversion { ConversionKind: ConversionKind.ExplicitNullable or ConversionKind.ImplicitNullable } conv && conv.Operand.Type!.IsNonNullableValueType()); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; // Returns true if `binary.Right` was visited by the call. bool learnFromOperator(BoundBinaryOperator binary) { // `true == a?.b(out x)` if (isKnownNullOrNotNull(binary.Left) && TryVisitConditionalAccess(binary.Right, out var stateWhenNotNull)) { var isNullConstant = binary.Left.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // `a && b(out x) == true` else if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); return true; } // `true == a && b(out x)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } return true; } return false; } } protected void VisitBinaryInterpolatedStringAddition(BoundBinaryOperator node) { Debug.Assert(node.InterpolatedStringHandlerData.HasValue); var stack = ArrayBuilder<BoundInterpolatedString>.GetInstance(); var data = node.InterpolatedStringHandlerData.GetValueOrDefault(); while (PushBinaryOperatorInterpolatedStringChildren(node, stack) is { } next) { node = next; } Debug.Assert(stack.Count >= 2); VisitRvalue(data.Construction); bool visitedFirst = false; bool hasTrailingHandlerValidityParameter = data.HasTrailingHandlerValidityParameter; bool hasConditionalEvaluation = data.UsesBoolReturns || hasTrailingHandlerValidityParameter; TLocalState? shortCircuitState = hasConditionalEvaluation ? State.Clone() : default; while (stack.TryPop(out var currentString)) { visitedFirst |= VisitInterpolatedStringHandlerParts(currentString, data.UsesBoolReturns, firstPartIsConditional: visitedFirst || hasTrailingHandlerValidityParameter, ref shortCircuitState); } if (hasConditionalEvaluation) { Join(ref State, ref shortCircuitState); } stack.Free(); } protected virtual BoundBinaryOperator? PushBinaryOperatorInterpolatedStringChildren(BoundBinaryOperator node, ArrayBuilder<BoundInterpolatedString> stack) { stack.Push((BoundInterpolatedString)node.Right); switch (node.Left) { case BoundBinaryOperator next: return next; case BoundInterpolatedString @string: stack.Push(@string); return null; default: throw ExceptionUtilities.UnexpectedValue(node.Left.Kind); } } protected virtual bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref TLocalState? shortCircuitState) { Debug.Assert(shortCircuitState != null || (!usesBoolReturns && !firstPartIsConditional)); if (node.Parts.IsEmpty) { return false; } ReadOnlySpan<BoundExpression> parts; if (firstPartIsConditional) { parts = node.Parts.AsSpan(); } else { VisitRvalue(node.Parts[0]); shortCircuitState = State.Clone(); parts = node.Parts.AsSpan()[1..]; } foreach (var part in parts) { VisitRvalue(part); if (usesBoolReturns) { Debug.Assert(shortCircuitState != null); Join(ref shortCircuitState, ref State); } } return true; } #nullable disable public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { if (node.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { // We have a special case for the ! unary operator, which can operate in a boolean context (5.3.3.26) VisitCondition(node.Operand); // it inverts the sense of assignedWhenTrue and assignedWhenFalse. SetConditionalState(StateWhenFalse, StateWhenTrue); } else { VisitRvalue(node.Operand); } return null; } public override BoundNode VisitRangeExpression(BoundRangeExpression node) { if (node.LeftOperandOpt != null) { VisitRvalue(node.LeftOperandOpt); } if (node.RightOperandOpt != null) { VisitRvalue(node.RightOperandOpt); } return null; } public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { VisitRvalue(node.Expression); PendingBranches.Add(new PendingBranch(node, this.State, null)); return null; } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { // TODO: should we also specially handle events? if (RegularPropertyAccess(node.Operand)) { var left = (BoundPropertyAccess)node.Operand; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var readMethod = GetReadMethod(property); var writeMethod = GetWriteMethod(property); Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)writeMethod); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); PropertySetter(node, left.ReceiverOpt, writeMethod); // followed by a write return null; } } VisitRvalue(node.Operand); return null; } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } if (node.InitializerOpt != null) { VisitArrayInitializationInternal(node, node.InitializerOpt); } return null; } private void VisitArrayInitializationInternal(BoundArrayCreation arrayCreation, BoundArrayInitialization node) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { VisitArrayInitializationInternal(arrayCreation, (BoundArrayInitialization)child); } else { VisitRvalue(child); } } } public override BoundNode VisitForStatement(BoundForStatement node) { if (node.Initializer != null) { VisitStatement(node.Initializer); } LoopHead(node); TLocalState bodyState, breakState; if (node.Condition != null) { VisitCondition(node.Condition); bodyState = this.StateWhenTrue; breakState = this.StateWhenFalse; } else { bodyState = this.State; breakState = UnreachableState(); } SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); if (node.Increment != null) { VisitStatement(node.Increment); } LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitForEachStatement(BoundForEachStatement node) { // foreach [await] ( var v in node.Expression ) { node.Body; node.ContinueLabel: } node.BreakLabel: VisitForEachExpression(node); var breakState = this.State.Clone(); LoopHead(node); VisitForEachIterationVariables(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); if (AwaitUsingAndForeachAddsPendingBranch && ((CommonForEachStatementSyntax)node.Syntax).AwaitKeyword != default) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return null; } protected virtual void VisitForEachExpression(BoundForEachStatement node) { VisitRvalue(node.Expression); } public virtual void VisitForEachIterationVariables(BoundForEachStatement node) { } public override BoundNode VisitAsOperator(BoundAsOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitIsOperator(BoundIsOperator node) { if (VisitPossibleConditionalAccess(node.Operand, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); SetConditionalState(stateWhenNotNull, State); } else { // `(a && b.M(out x)) is bool` should discard conditional state from LHS Unsplit(); } return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { if (node.ReceiverOpt != null) { // An explicit or implicit receiver, for example in an expression such as (x.Goo is Action, or Goo is Action), is considered to be read. VisitRvalue(node.ReceiverOpt); } return null; } #nullable enable public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { if (IsConstantNull(node.LeftOperand)) { VisitRvalue(node.LeftOperand); Visit(node.RightOperand); } else { TLocalState savedState; if (VisitPossibleConditionalAccess(node.LeftOperand, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); savedState = stateWhenNotNull; } else { Unsplit(); savedState = State.Clone(); } if (node.LeftOperand.ConstantValue != null) { SetUnreachable(); } Visit(node.RightOperand); if (IsConditionalState) { Join(ref StateWhenTrue, ref savedState); Join(ref StateWhenFalse, ref savedState); } else { Join(ref this.State, ref savedState); } } return null; } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) { var access = node switch { BoundConditionalAccess ca => ca, BoundConversion { Conversion: Conversion conversion, Operand: BoundConditionalAccess ca } when CanPropagateStateWhenNotNull(conversion) => ca, _ => null }; if (access is not null) { EnterRegionIfNeeded(access); Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); Debug.Assert(!IsConditionalState); LeaveRegionIfNeeded(access); return true; } stateWhenNotNull = default; return false; } /// <summary> /// "State when not null" can only propagate out of a conditional access if /// it is not subject to a user-defined conversion whose parameter is not of a non-nullable value type. /// </summary> protected static bool CanPropagateStateWhenNotNull(Conversion conversion) { if (!conversion.IsValid) { return false; } if (!conversion.IsUserDefined) { return true; } var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount is 1); var param = method.Parameters[0]; return param.Type.IsNonNullableValueType(); } /// <summary> /// Unconditionally visits an expression. /// If the expression has "state when not null" after visiting, /// the method returns 'true' and writes the state to <paramref name="stateWhenNotNull" />. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } else { Visit(node); return false; } } private void VisitConditionalAccess(BoundConditionalAccess node, out TLocalState stateWhenNotNull) { // The receiver may also be a conditional access. // `(a?.b(x = 1))?.c(y = 1)` if (VisitPossibleConditionalAccess(node.Receiver, out var receiverStateWhenNotNull)) { stateWhenNotNull = receiverStateWhenNotNull; } else { Unsplit(); stateWhenNotNull = this.State.Clone(); } if (node.Receiver.ConstantValue != null && !IsConstantNull(node.Receiver)) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull if (VisitPossibleConditionalAccess(node.AccessExpression, out var firstAccessStateWhenNotNull)) { stateWhenNotNull = firstAccessStateWhenNotNull; } else { Unsplit(); stateWhenNotNull = this.State.Clone(); } } else { var savedState = this.State.Clone(); if (IsConstantNull(node.Receiver)) { SetUnreachable(); } else { SetState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. VisitRvalue(innerCondAccess.Receiver); expr = innerCondAccess.AccessExpression; // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); } Debug.Assert(expr is BoundExpression); VisitRvalue(expr); stateWhenNotNull = State; State = savedState; Join(ref State, ref stateWhenNotNull); } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, stateWhenNotNull: out _); return null; } #nullable disable public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) { VisitRvalue(node.Receiver); var savedState = this.State.Clone(); VisitRvalue(node.WhenNotNull); Join(ref this.State, ref savedState); if (node.WhenNullOpt != null) { savedState = this.State.Clone(); VisitRvalue(node.WhenNullOpt); Join(ref this.State, ref savedState); } return null; } public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) { return null; } public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) { var savedState = this.State.Clone(); VisitRvalue(node.ValueTypeReceiver); Join(ref this.State, ref savedState); savedState = this.State.Clone(); VisitRvalue(node.ReferenceTypeReceiver); Join(ref this.State, ref savedState); return null; } public override BoundNode VisitSequence(BoundSequence node) { var sideEffects = node.SideEffects; if (!sideEffects.IsEmpty) { foreach (var se in sideEffects) { VisitRvalue(se); } } VisitRvalue(node.Value); return null; } public override BoundNode VisitSequencePoint(BoundSequencePoint node) { if (node.StatementOpt != null) { VisitStatement(node.StatementOpt); } return null; } public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node) { if (node.StatementOpt != null) { VisitStatement(node.StatementOpt); } return null; } public override BoundNode VisitStatementList(BoundStatementList node) { return VisitStatementListWorker(node); } private BoundNode VisitStatementListWorker(BoundStatementList node) { foreach (var statement in node.Statements) { VisitStatement(statement); } return null; } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { return VisitStatementListWorker(node); } public override BoundNode VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. return VisitLambda(node.BindForErrorRecovery()); } public override BoundNode VisitBreakStatement(BoundBreakStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } public override BoundNode VisitContinueStatement(BoundContinueStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } public override BoundNode VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) { return VisitConditionalOperatorCore(node, isByRef: false, node.Condition, node.Consequence, node.Alternative); } public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { return VisitConditionalOperatorCore(node, node.IsRef, node.Condition, node.Consequence, node.Alternative); } #nullable enable protected virtual BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isByRef, BoundExpression condition, BoundExpression consequence, BoundExpression alternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; if (IsConstantTrue(condition)) { VisitConditionalOperand(alternativeState, alternative, isByRef); VisitConditionalOperand(consequenceState, consequence, isByRef); } else if (IsConstantFalse(condition)) { VisitConditionalOperand(consequenceState, consequence, isByRef); VisitConditionalOperand(alternativeState, alternative, isByRef); } else { // at this point, the state is conditional after a conditional expression if: // 1. the state is conditional after the consequence, or // 2. the state is conditional after the alternative VisitConditionalOperand(consequenceState, consequence, isByRef); var conditionalAfterConsequence = IsConditionalState; var (afterConsequenceWhenTrue, afterConsequenceWhenFalse) = conditionalAfterConsequence ? (StateWhenTrue, StateWhenFalse) : (State, State); VisitConditionalOperand(alternativeState, alternative, isByRef); if (!conditionalAfterConsequence && !IsConditionalState) { // simplify in the common case Join(ref this.State, ref afterConsequenceWhenTrue); } else { Split(); Join(ref this.StateWhenTrue, ref afterConsequenceWhenTrue); Join(ref this.StateWhenFalse, ref afterConsequenceWhenFalse); } } return null; } #nullable disable private void VisitConditionalOperand(TLocalState state, BoundExpression operand, bool isByRef) { SetState(state); if (isByRef) { VisitLvalue(operand); // exposing ref is a potential write WriteArgument(operand, RefKind.Ref, method: null); } else { Visit(operand); } } public override BoundNode VisitBaseReference(BoundBaseReference node) { return null; } public override BoundNode VisitDoStatement(BoundDoStatement node) { // do { statements; node.ContinueLabel: } while (node.Condition) node.BreakLabel: LoopHead(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); VisitCondition(node.Condition); TLocalState breakState = this.StateWhenFalse; SetState(this.StateWhenTrue); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } protected void VisitLabel(LabelSymbol label, BoundStatement node) { node.AssertIsLabeledStatementWithLabel(label); ResolveBranches(label, node); var state = LabelState(label); Join(ref this.State, ref state); _labels[label] = this.State.Clone(); _labelsSeen.Add(node); } protected virtual void VisitLabel(BoundLabeledStatement node) { VisitLabel(node.Label, node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { VisitLabel(node.Label, node); return null; } public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) { VisitLabel(node); VisitStatement(node.Body); return null; } public override BoundNode VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode VisitNoOpStatement(BoundNoOpStatement node) { return null; } public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node) { return null; } public override BoundNode VisitUsingStatement(BoundUsingStatement node) { if (node.ExpressionOpt != null) { VisitRvalue(node.ExpressionOpt); } if (node.DeclarationsOpt != null) { VisitStatement(node.DeclarationsOpt); } VisitStatement(node.Body); if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return null; } public abstract bool AwaitUsingAndForeachAddsPendingBranch { get; } public override BoundNode VisitFixedStatement(BoundFixedStatement node) { VisitStatement(node.Declarations); VisitStatement(node.Body); return null; } public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { BoundExpression expr = node.ExpressionOpt; VisitRvalue(expr); SetUnreachable(); return null; } public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, null)); SetUnreachable(); return null; } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { VisitRvalue(node.Expression); PendingBranches.Add(new PendingBranch(node, this.State, null)); return null; } public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) { return null; } public override BoundNode VisitDefaultExpression(BoundDefaultExpression node) { return null; } public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { VisitTypeExpression(node.SourceType); return null; } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { var savedState = this.State; SetState(UnreachableState()); Visit(node.Argument); SetState(savedState); return null; } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { VisitAddressOfOperand(node.Operand, shouldReadOperand: false); return null; } protected void VisitAddressOfOperand(BoundExpression operand, bool shouldReadOperand) { if (shouldReadOperand) { this.VisitRvalue(operand); } else { this.VisitLvalue(operand); } this.WriteArgument(operand, RefKind.Out, null); //Out because we know it will definitely be assigned. } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { VisitRvalue(node.Expression); VisitRvalue(node.Index); return null; } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { return null; } private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node) { VisitRvalue(node.Count); if (node.InitializerOpt != null && !node.InitializerOpt.Initializers.IsDefault) { foreach (var element in node.InitializerOpt.Initializers) { VisitRvalue(element); } } return null; } public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { return VisitStackAllocArrayCreationBase(node); } public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { return VisitStackAllocArrayCreationBase(node); } public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { // visit arguments as r-values VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.Constructor); return null; } public override BoundNode VisitArrayLength(BoundArrayLength node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { VisitCondition(node.Condition); Debug.Assert(this.IsConditionalState); if (node.JumpIfTrue) { PendingBranches.Add(new PendingBranch(node, this.StateWhenTrue, node.Label)); this.SetState(this.StateWhenFalse); } else { PendingBranches.Add(new PendingBranch(node, this.StateWhenFalse, node.Label)); this.SetState(this.StateWhenTrue); } return null; } public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } private BoundNode VisitObjectOrCollectionInitializerExpression(ImmutableArray<BoundExpression> initializers) { foreach (var initializer in initializers) { VisitRvalue(initializer); } return null; } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { var arguments = node.Arguments; if (!arguments.IsDefaultOrEmpty) { MethodSymbol method = null; if (node.MemberSymbol?.Kind == SymbolKind.Property) { var property = (PropertySymbol)node.MemberSymbol; method = GetReadMethod(property); } VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); } return null; } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { return null; } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (node.AddMethod.CallsAreOmitted(node.SyntaxTree)) { // If the underlying add method is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // flow analysis. TLocalState savedState = savedState = this.State.Clone(); SetUnreachable(); VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); this.State = savedState; } else { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); } return null; } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), method: null); return null; } public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node) { return null; } public override BoundNode VisitFieldEqualsValue(BoundFieldEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitPropertyEqualsValue(BoundPropertyEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitParameterEqualsValue(BoundParameterEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { return null; } public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { return null; } public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { return null; } public sealed override BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node) { throw ExceptionUtilities.Unreachable; } public sealed override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDiscardExpression(BoundDiscardExpression node) { return null; } private static MethodSymbol GetReadMethod(PropertySymbol property) => property.GetOwnOrInheritedGetMethod() ?? property.SetMethod; private static MethodSymbol GetWriteMethod(PropertySymbol property) => property.GetOwnOrInheritedSetMethod() ?? property.GetMethod; public override BoundNode VisitConstructorMethodBody(BoundConstructorMethodBody node) { Visit(node.Initializer); VisitMethodBodies(node.BlockBody, node.ExpressionBody); return null; } public override BoundNode VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node) { VisitMethodBodies(node.BlockBody, node.ExpressionBody); return null; } public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { TLocalState leftState; if (RegularPropertyAccess(node.LeftOperand) && (BoundPropertyAccess)node.LeftOperand is var left && left.PropertySymbol is var property && property.RefKind == RefKind.None) { var readMethod = property.GetOwnOrInheritedGetMethod(); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); var savedState = this.State.Clone(); AdjustStateForNullCoalescingAssignmentNonNullCase(node); leftState = this.State.Clone(); SetState(savedState); VisitAssignmentOfNullCoalescingAssignment(node, left); } else { VisitRvalue(node.LeftOperand, isKnownToBeAnLvalue: true); var savedState = this.State.Clone(); AdjustStateForNullCoalescingAssignmentNonNullCase(node); leftState = this.State.Clone(); SetState(savedState); VisitAssignmentOfNullCoalescingAssignment(node, propertyAccessOpt: null); } Join(ref this.State, ref leftState); return null; } public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { Visit(node.InvokedExpression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature); return null; } public override BoundNode VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) { // This is not encountered in correct programs, but can be seen if the function pointer was // unable to be converted and the semantic model is used to query for information. Visit(node.Operand); return null; } /// <summary> /// This visitor represents just the assignment part of the null coalescing assignment /// operator. /// </summary> protected virtual void VisitAssignmentOfNullCoalescingAssignment( BoundNullCoalescingAssignmentOperator node, BoundPropertyAccess propertyAccessOpt) { VisitRvalue(node.RightOperand); if (propertyAccessOpt != null) { var symbol = propertyAccessOpt.PropertySymbol; var writeMethod = symbol.GetOwnOrInheritedSetMethod(); PropertySetter(node, propertyAccessOpt.ReceiverOpt, writeMethod); } } public override BoundNode VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node) { return null; } public override BoundNode VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) { return null; } public override BoundNode VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node) { return null; } /// <summary> /// This visitor represents just the non-assignment part of the null coalescing assignment /// operator (when the left operand is non-null). /// </summary> protected virtual void AdjustStateForNullCoalescingAssignmentNonNullCase(BoundNullCoalescingAssignmentOperator node) { } private void VisitMethodBodies(BoundBlock blockBody, BoundBlock expressionBody) { if (blockBody == null) { Visit(expressionBody); return; } else if (expressionBody == null) { Visit(blockBody); return; } // In error cases we have two bodies. These are two unrelated pieces of code, // they are not executed one after another. As we don't really know which one the developer // intended to use, we need to visit both. We are going to pretend that there is // an unconditional fork in execution and then we are converging after each body is executed. // For example, if only one body assigns an out parameter, then after visiting both bodies // we should consider that parameter is not definitely assigned. // Note, that today this code is not executed for regular definite assignment analysis. It is // only executed for region analysis. TLocalState initialState = this.State.Clone(); Visit(blockBody); TLocalState afterBlock = this.State; SetState(initialState); Visit(expressionBody); Join(ref this.State, ref afterBlock); } #endregion visitors } /// <summary> /// The possible places that we are processing when there is a region. /// </summary> /// <remarks> /// This should be nested inside <see cref="AbstractFlowPass{TLocalState, TLocalFunctionState}"/> but is not due to https://github.com/dotnet/roslyn/issues/36992 . /// </remarks> internal enum RegionPlace { Before, Inside, After }; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// An abstract flow pass that takes some shortcuts in analyzing finally blocks, in order to enable /// the analysis to take place without tracking exceptions or repeating the analysis of a finally block /// for each exit from a try statement. The shortcut results in a slightly less precise /// (but still conservative) analysis, but that less precise analysis is all that is required for /// the language specification. The most significant shortcut is that we do not track the state /// where exceptions can arise. That does not affect the soundness for most analyses, but for those /// analyses whose soundness would be affected (e.g. "data flows out"), we track "unassignments" to keep /// the analysis sound. /// </summary> /// <remarks> /// Formally, this is a fairly conventional lattice flow analysis (<see /// href="https://en.wikipedia.org/wiki/Data-flow_analysis"/>) that moves upward through the <see cref="Join(ref /// TLocalState, ref TLocalState)"/> operation. /// </remarks> internal abstract partial class AbstractFlowPass<TLocalState, TLocalFunctionState> : BoundTreeVisitor where TLocalState : AbstractFlowPass<TLocalState, TLocalFunctionState>.ILocalState where TLocalFunctionState : AbstractFlowPass<TLocalState, TLocalFunctionState>.AbstractLocalFunctionState { protected int _recursionDepth; /// <summary> /// The compilation in which the analysis is taking place. This is needed to determine which /// conditional methods will be compiled and which will be omitted. /// </summary> protected readonly CSharpCompilation compilation; /// <summary> /// The method whose body is being analyzed, or the field whose initializer is being analyzed. /// May be a top-level member or a lambda or local function. It is used for /// references to method parameters. Thus, '_symbol' should not be used directly, but /// 'MethodParameters', 'MethodThisParameter' and 'AnalyzeOutParameters(...)' should be used /// instead. _symbol is null during speculative binding. /// </summary> protected readonly Symbol _symbol; /// <summary> /// Reflects the enclosing member, lambda or local function at the current location (in the bound tree). /// </summary> protected Symbol CurrentSymbol; /// <summary> /// The bound node of the method or initializer being analyzed. /// </summary> protected readonly BoundNode methodMainNode; /// <summary> /// The flow analysis state at each label, computed by calling <see cref="Join(ref /// TLocalState, ref TLocalState)"/> on the state from branches to that label with the state /// when we fall into the label. Entries are created when the label is encountered. One /// case deserves special attention: when the destination of the branch is a label earlier /// in the code, it is possible (though rarely occurs in practice) that we are changing the /// state at a label that we've already analyzed. In that case we run another pass of the /// analysis to allow those changes to propagate. This repeats until no further changes to /// the state of these labels occurs. This can result in quadratic performance in unlikely /// but possible code such as this: "int x; if (cond) goto l1; x = 3; l5: print x; l4: goto /// l5; l3: goto l4; l2: goto l3; l1: goto l2;" /// </summary> private readonly PooledDictionary<LabelSymbol, TLocalState> _labels; /// <summary> /// Set to true after an analysis scan if the analysis was incomplete due to state changing /// after it was used by another analysis component. In this case the caller scans again (until /// this is false). Since the analysis proceeds by monotonically changing the state computed /// at each label, this must terminate. /// </summary> protected bool stateChangedAfterUse; /// <summary> /// All of the labels seen so far in this forward scan of the body /// </summary> private PooledHashSet<BoundStatement> _labelsSeen; /// <summary> /// Pending escapes generated in the current scope (or more deeply nested scopes). When jump /// statements (goto, break, continue, return) are processed, they are placed in the /// pendingBranches buffer to be processed later by the code handling the destination /// statement. As a special case, the processing of try-finally statements might modify the /// contents of the pendingBranches buffer to take into account the behavior of /// "intervening" finally clauses. /// </summary> protected ArrayBuilder<PendingBranch> PendingBranches { get; private set; } /// <summary> /// The definite assignment and/or reachability state at the point currently being analyzed. /// </summary> protected TLocalState State; protected TLocalState StateWhenTrue; protected TLocalState StateWhenFalse; protected bool IsConditionalState; /// <summary> /// Indicates that the transfer function for a particular node (the function mapping the /// state before the node to the state after the node) is not monotonic, in the sense that /// it can change the state in either direction in the lattice. If the transfer function is /// monotonic, the transfer function can only change the state toward the <see /// cref="UnreachableState"/>. Reachability and definite assignment are monotonic, and /// permit a more efficient analysis. Region analysis and nullable analysis are not /// monotonic. This is just an optimization; we could treat all of them as nonmonotonic /// without much loss of performance. In fact, this only affects the analysis of (relatively /// rare) try statements, and is only a slight optimization. /// </summary> private readonly bool _nonMonotonicTransfer; protected void SetConditionalState((TLocalState whenTrue, TLocalState whenFalse) state) { SetConditionalState(state.whenTrue, state.whenFalse); } protected void SetConditionalState(TLocalState whenTrue, TLocalState whenFalse) { IsConditionalState = true; State = default(TLocalState); StateWhenTrue = whenTrue; StateWhenFalse = whenFalse; } protected void SetState(TLocalState newState) { Debug.Assert(newState != null); StateWhenTrue = StateWhenFalse = default(TLocalState); IsConditionalState = false; State = newState; } protected void Split() { if (!IsConditionalState) { SetConditionalState(State, State.Clone()); } } protected void Unsplit() { if (IsConditionalState) { Join(ref StateWhenTrue, ref StateWhenFalse); SetState(StateWhenTrue); } } /// <summary> /// Where all diagnostics are deposited. /// </summary> protected DiagnosticBag Diagnostics { get; } #region Region // For region analysis, we maintain some extra data. protected RegionPlace regionPlace; // tells whether we are currently analyzing code before, during, or after the region protected readonly BoundNode firstInRegion, lastInRegion; protected readonly bool TrackingRegions; /// <summary> /// A cache of the state at the backward branch point of each loop. This is not needed /// during normal flow analysis, but is needed for DataFlowsOut region analysis. /// </summary> private readonly Dictionary<BoundLoopStatement, TLocalState> _loopHeadState; #endregion Region protected AbstractFlowPass( CSharpCompilation compilation, Symbol symbol, BoundNode node, BoundNode firstInRegion = null, BoundNode lastInRegion = null, bool trackRegions = false, bool nonMonotonicTransferFunction = false) { Debug.Assert(node != null); if (firstInRegion != null && lastInRegion != null) { trackRegions = true; } if (trackRegions) { Debug.Assert(firstInRegion != null); Debug.Assert(lastInRegion != null); int startLocation = firstInRegion.Syntax.SpanStart; int endLocation = lastInRegion.Syntax.Span.End; int length = endLocation - startLocation; Debug.Assert(length >= 0, "last comes before first"); this.RegionSpan = new TextSpan(startLocation, length); } PendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); _labels = PooledDictionary<LabelSymbol, TLocalState>.GetInstance(); this.Diagnostics = DiagnosticBag.GetInstance(); this.compilation = compilation; _symbol = symbol; CurrentSymbol = symbol; this.methodMainNode = node; this.firstInRegion = firstInRegion; this.lastInRegion = lastInRegion; _loopHeadState = new Dictionary<BoundLoopStatement, TLocalState>(ReferenceEqualityComparer.Instance); TrackingRegions = trackRegions; _nonMonotonicTransfer = nonMonotonicTransferFunction; } protected abstract string Dump(TLocalState state); protected string Dump() { return IsConditionalState ? $"true: {Dump(this.StateWhenTrue)} false: {Dump(this.StateWhenFalse)}" : Dump(this.State); } #if DEBUG protected string DumpLabels() { StringBuilder result = new StringBuilder(); result.Append("Labels{"); bool first = true; foreach (var key in _labels.Keys) { if (!first) { result.Append(", "); } string name = key.Name; if (string.IsNullOrEmpty(name)) { name = "<Label>" + key.GetHashCode(); } result.Append(name).Append(": ").Append(this.Dump(_labels[key])); first = false; } result.Append("}"); return result.ToString(); } #endif private void EnterRegionIfNeeded(BoundNode node) { if (TrackingRegions && node == this.firstInRegion && this.regionPlace == RegionPlace.Before) { EnterRegion(); } } /// <summary> /// Subclasses may override EnterRegion to perform any actions at the entry to the region. /// </summary> protected virtual void EnterRegion() { Debug.Assert(this.regionPlace == RegionPlace.Before); this.regionPlace = RegionPlace.Inside; } private void LeaveRegionIfNeeded(BoundNode node) { if (TrackingRegions && node == this.lastInRegion && this.regionPlace == RegionPlace.Inside) { LeaveRegion(); } } /// <summary> /// Subclasses may override LeaveRegion to perform any action at the end of the region. /// </summary> protected virtual void LeaveRegion() { Debug.Assert(IsInside); this.regionPlace = RegionPlace.After; } protected readonly TextSpan RegionSpan; protected bool RegionContains(TextSpan span) { // TODO: There are no scenarios involving a zero-length span // currently. If the assert fails, add a corresponding test. Debug.Assert(span.Length > 0); if (span.Length == 0) { return RegionSpan.Contains(span.Start); } return RegionSpan.Contains(span); } protected bool IsInside { get { return regionPlace == RegionPlace.Inside; } } protected virtual void EnterParameters(ImmutableArray<ParameterSymbol> parameters) { foreach (var parameter in parameters) { EnterParameter(parameter); } } protected virtual void EnterParameter(ParameterSymbol parameter) { } protected virtual void LeaveParameters( ImmutableArray<ParameterSymbol> parameters, SyntaxNode syntax, Location location) { foreach (ParameterSymbol parameter in parameters) { LeaveParameter(parameter, syntax, location); } } protected virtual void LeaveParameter(ParameterSymbol parameter, SyntaxNode syntax, Location location) { } public override BoundNode Visit(BoundNode node) { return VisitAlways(node); } protected BoundNode VisitAlways(BoundNode node) { BoundNode result = null; // We scan even expressions, because we must process lambdas contained within them. if (node != null) { EnterRegionIfNeeded(node); VisitWithStackGuard(node); LeaveRegionIfNeeded(node); } return result; } [DebuggerStepThrough] private BoundNode VisitWithStackGuard(BoundNode node) { var expression = node as BoundExpression; if (expression != null) { return VisitExpressionWithStackGuard(ref _recursionDepth, expression); } return base.Visit(node); } [DebuggerStepThrough] protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)base.Visit(node); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return false; // just let the original exception bubble up. } /// <summary> /// A pending branch. These are created for a return, break, continue, goto statement, /// yield return, yield break, await expression, and await foreach/using. The idea is that /// we don't know if the branch will eventually reach its destination because of an /// intervening finally block that cannot complete normally. So we store them up and handle /// them as we complete processing each construct. At the end of a block, if there are any /// pending branches to a label in that block we process the branch. Otherwise we relay it /// up to the enclosing construct as a pending branch of the enclosing construct. /// </summary> internal class PendingBranch { public readonly BoundNode Branch; public bool IsConditionalState; public TLocalState State; public TLocalState StateWhenTrue; public TLocalState StateWhenFalse; public readonly LabelSymbol Label; public PendingBranch(BoundNode branch, TLocalState state, LabelSymbol label, bool isConditionalState = false, TLocalState stateWhenTrue = default, TLocalState stateWhenFalse = default) { this.Branch = branch; this.State = state.Clone(); this.IsConditionalState = isConditionalState; if (isConditionalState) { this.StateWhenTrue = stateWhenTrue.Clone(); this.StateWhenFalse = stateWhenFalse.Clone(); } this.Label = label; } } /// <summary> /// Perform a single pass of flow analysis. Note that after this pass, /// this.backwardBranchChanged indicates if a further pass is required. /// </summary> protected virtual ImmutableArray<PendingBranch> Scan(ref bool badRegion) { var oldPending = SavePending(); Visit(methodMainNode); this.Unsplit(); RestorePending(oldPending); if (TrackingRegions && regionPlace != RegionPlace.After) { badRegion = true; } ImmutableArray<PendingBranch> result = RemoveReturns(); return result; } protected ImmutableArray<PendingBranch> Analyze(ref bool badRegion, Optional<TLocalState> initialState = default) { ImmutableArray<PendingBranch> returns; do { // the entry point of a method is assumed reachable regionPlace = RegionPlace.Before; this.State = initialState.HasValue ? initialState.Value : TopState(); PendingBranches.Clear(); this.stateChangedAfterUse = false; this.Diagnostics.Clear(); returns = this.Scan(ref badRegion); } while (this.stateChangedAfterUse); return returns; } protected virtual void Free() { this.Diagnostics.Free(); PendingBranches.Free(); _labelsSeen.Free(); _labels.Free(); } /// <summary> /// If a method is currently being analyzed returns its parameters, returns an empty array /// otherwise. /// </summary> protected ImmutableArray<ParameterSymbol> MethodParameters { get { var method = _symbol as MethodSymbol; return (object)method == null ? ImmutableArray<ParameterSymbol>.Empty : method.Parameters; } } /// <summary> /// If a method is currently being analyzed returns its 'this' parameter, returns null /// otherwise. /// </summary> protected ParameterSymbol MethodThisParameter { get { ParameterSymbol thisParameter = null; (_symbol as MethodSymbol)?.TryGetThisParameter(out thisParameter); return thisParameter; } } /// <summary> /// Specifies whether or not method's out parameters should be analyzed. If there's more /// than one location in the method being analyzed, then the method is partial and we prefer /// to report an out parameter in partial method error. /// </summary> /// <param name="location">location to be used</param> /// <returns>true if the out parameters of the method should be analyzed</returns> protected bool ShouldAnalyzeOutParameters(out Location location) { var method = _symbol as MethodSymbol; if ((object)method == null || method.Locations.Length != 1) { location = null; return false; } else { location = method.Locations[0]; return true; } } /// <summary> /// Return the flow analysis state associated with a label. /// </summary> /// <param name="label"></param> /// <returns></returns> protected virtual TLocalState LabelState(LabelSymbol label) { TLocalState result; if (_labels.TryGetValue(label, out result)) { return result; } result = UnreachableState(); _labels.Add(label, result); return result; } /// <summary> /// Return to the caller the set of pending return statements. /// </summary> /// <returns></returns> protected virtual ImmutableArray<PendingBranch> RemoveReturns() { ImmutableArray<PendingBranch> result; result = PendingBranches.ToImmutable(); PendingBranches.Clear(); // The caller should have handled and cleared labelsSeen. Debug.Assert(_labelsSeen.Count == 0); return result; } /// <summary> /// Set the current state to one that indicates that it is unreachable. /// </summary> protected void SetUnreachable() { this.State = UnreachableState(); } protected void VisitLvalue(BoundExpression node) { EnterRegionIfNeeded(node); switch (node?.Kind) { case BoundKind.Parameter: VisitLvalueParameter((BoundParameter)node); break; case BoundKind.Local: VisitLvalue((BoundLocal)node); break; case BoundKind.ThisReference: case BoundKind.BaseReference: break; case BoundKind.PropertyAccess: var access = (BoundPropertyAccess)node; if (Binder.AccessingAutoPropertyFromConstructor(access, _symbol)) { var backingField = (access.PropertySymbol as SourcePropertySymbolBase)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(access.ReceiverOpt, backingField); break; } } goto default; case BoundKind.FieldAccess: { BoundFieldAccess node1 = (BoundFieldAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.FieldSymbol); break; } case BoundKind.EventAccess: { BoundEventAccess node1 = (BoundEventAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.EventSymbol.AssociatedField); break; } case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: ((BoundTupleExpression)node).VisitAllElements((x, self) => self.VisitLvalue(x), this); break; default: VisitRvalue(node); break; } LeaveRegionIfNeeded(node); } protected virtual void VisitLvalue(BoundLocal node) { } /// <summary> /// Visit a boolean condition expression. /// </summary> /// <param name="node"></param> protected void VisitCondition(BoundExpression node) { Visit(node); AdjustConditionalState(node); } private void AdjustConditionalState(BoundExpression node) { if (IsConstantTrue(node)) { Unsplit(); SetConditionalState(this.State, UnreachableState()); } else if (IsConstantFalse(node)) { Unsplit(); SetConditionalState(UnreachableState(), this.State); } else if ((object)node.Type == null || node.Type.SpecialType != SpecialType.System_Boolean) { // a dynamic type or a type with operator true/false Unsplit(); } Split(); } /// <summary> /// Visit a general expression, where we will only need to determine if variables are /// assigned (or not). That is, we will not be needing AssignedWhenTrue and /// AssignedWhenFalse. /// </summary> /// <param name="isKnownToBeAnLvalue">True when visiting an rvalue that will actually be used as an lvalue, /// for example a ref parameter when simulating a read of it, or an argument corresponding to an in parameter</param> protected virtual void VisitRvalue(BoundExpression node, bool isKnownToBeAnLvalue = false) { Visit(node); Unsplit(); } /// <summary> /// Visit a statement. /// </summary> [DebuggerHidden] protected virtual void VisitStatement(BoundStatement statement) { Visit(statement); Debug.Assert(!this.IsConditionalState); } protected static bool IsConstantTrue(BoundExpression node) { return node.ConstantValue == ConstantValue.True; } protected static bool IsConstantFalse(BoundExpression node) { return node.ConstantValue == ConstantValue.False; } protected static bool IsConstantNull(BoundExpression node) { return node.ConstantValue == ConstantValue.Null; } /// <summary> /// Called at the point in a loop where the backwards branch would go to. /// </summary> private void LoopHead(BoundLoopStatement node) { TLocalState previousState; if (_loopHeadState.TryGetValue(node, out previousState)) { Join(ref this.State, ref previousState); } _loopHeadState[node] = this.State.Clone(); } /// <summary> /// Called at the point in a loop where the backward branch is placed. /// </summary> private void LoopTail(BoundLoopStatement node) { var oldState = _loopHeadState[node]; if (Join(ref oldState, ref this.State)) { _loopHeadState[node] = oldState; this.stateChangedAfterUse = true; } } /// <summary> /// Used to resolve break statements in each statement form that has a break statement /// (loops, switch). /// </summary> private void ResolveBreaks(TLocalState breakState, LabelSymbol label) { var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { Join(ref breakState, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } SetState(breakState); } /// <summary> /// Used to resolve continue statements in each statement form that supports it. /// </summary> private void ResolveContinues(LabelSymbol continueLabel) { var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == continueLabel) { // Technically, nothing in the language specification depends on the state // at the continue label, so we could just discard them instead of merging // the states. In fact, we need not have added continue statements to the // pending jump queue in the first place if we were interested solely in the // flow analysis. However, region analysis (in support of extract method) // and other forms of more precise analysis // depend on continue statements appearing in the pending branch queue, so // we process them from the queue here. Join(ref this.State, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } } /// <summary> /// Subclasses override this if they want to take special actions on processing a goto /// statement, when both the jump and the label have been located. /// </summary> protected virtual void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement target) { target.AssertIsLabeledStatement(); } /// <summary> /// To handle a label, we resolve all branches to that label. Returns true if the state of /// the label changes as a result. /// </summary> /// <param name="label">Target label</param> /// <param name="target">Statement containing the target label</param> private bool ResolveBranches(LabelSymbol label, BoundStatement target) { target?.AssertIsLabeledStatementWithLabel(label); bool labelStateChanged = false; var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { ResolveBranch(pending, label, target, ref labelStateChanged); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } return labelStateChanged; } protected virtual void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged) { var state = LabelState(label); if (target != null) { NoteBranch(pending, pending.Branch, target); } var changed = Join(ref state, ref pending.State); if (changed) { labelStateChanged = true; _labels[label] = state; } } protected struct SavedPending { public readonly ArrayBuilder<PendingBranch> PendingBranches; public readonly PooledHashSet<BoundStatement> LabelsSeen; public SavedPending(ArrayBuilder<PendingBranch> pendingBranches, PooledHashSet<BoundStatement> labelsSeen) { this.PendingBranches = pendingBranches; this.LabelsSeen = labelsSeen; } } /// <summary> /// Since branches cannot branch into constructs, only out, we save the pending branches /// when visiting more nested constructs. When tracking exceptions, we store the current /// state as the exception state for the following code. /// </summary> protected SavedPending SavePending() { Debug.Assert(!this.IsConditionalState); var result = new SavedPending(PendingBranches, _labelsSeen); PendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); return result; } /// <summary> /// We use this when closing a block that may contain labels or branches /// - branches to new labels are resolved /// - new labels are removed (no longer can be reached) /// - unresolved pending branches are carried forward /// </summary> /// <param name="oldPending">The old pending branches, which are to be merged with the current ones</param> protected void RestorePending(SavedPending oldPending) { foreach (var node in _labelsSeen) { switch (node.Kind) { case BoundKind.LabeledStatement: { var label = (BoundLabeledStatement)node; stateChangedAfterUse |= ResolveBranches(label.Label, label); } break; case BoundKind.LabelStatement: { var label = (BoundLabelStatement)node; stateChangedAfterUse |= ResolveBranches(label.Label, label); } break; case BoundKind.SwitchSection: { var sec = (BoundSwitchSection)node; foreach (var label in sec.SwitchLabels) { stateChangedAfterUse |= ResolveBranches(label.Label, sec); } } break; default: // there are no other kinds of labels throw ExceptionUtilities.UnexpectedValue(node.Kind); } } oldPending.PendingBranches.AddRange(this.PendingBranches); PendingBranches.Free(); PendingBranches = oldPending.PendingBranches; // We only use SavePending/RestorePending when there could be no branch into the region between them. // So there is no need to save the labels seen between the calls. If there were such a need, we would // do "this.labelsSeen.UnionWith(oldPending.LabelsSeen);" instead of the following assignment _labelsSeen.Free(); _labelsSeen = oldPending.LabelsSeen; } #region visitors /// <summary> /// Since each language construct must be handled according to the rules of the language specification, /// the default visitor reports that the construct for the node is not implemented in the compiler. /// </summary> public override BoundNode DefaultVisit(BoundNode node) { Debug.Assert(false, $"Should Visit{node.Kind} be overridden in {this.GetType().Name}?"); Diagnostics.Add(ErrorCode.ERR_InternalError, node.Syntax.Location); return null; } public override BoundNode VisitAttribute(BoundAttribute node) { // No flow analysis is ever done in attributes (or their arguments). return null; } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { VisitRvalue(node.Expression); SetUnreachable(); return node; } public override BoundNode VisitPassByCopy(BoundPassByCopy node) { VisitRvalue(node.Expression); return node; } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { Debug.Assert(!IsConditionalState); bool negated = node.Pattern.IsNegated(out var pattern); Debug.Assert(negated == node.IsNegated); if (VisitPossibleConditionalAccess(node.Expression, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); SetConditionalState(patternMatchesNull(pattern) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } else if (IsConditionalState) { // Patterns which only match a single boolean value should propagate conditional state // for example, `(a != null && a.M(out x)) is true` should have the same conditional state as `(a != null && a.M(out x))`. if (isBoolTest(pattern) is bool value) { if (!value) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { // Patterns which match more than a single boolean value cannot propagate conditional state // for example, `(a != null && a.M(out x)) is bool b` should not have conditional state Unsplit(); } } VisitPattern(pattern); var reachableLabels = node.DecisionDag.ReachableLabels; if (!reachableLabels.Contains(node.WhenTrueLabel)) { SetState(this.StateWhenFalse); SetConditionalState(UnreachableState(), this.State); } else if (!reachableLabels.Contains(node.WhenFalseLabel)) { SetState(this.StateWhenTrue); SetConditionalState(this.State, UnreachableState()); } if (negated) { SetConditionalState(this.StateWhenFalse, this.StateWhenTrue); } return node; static bool patternMatchesNull(BoundPattern pattern) { switch (pattern) { case BoundTypePattern: case BoundRecursivePattern: case BoundITuplePattern: case BoundRelationalPattern: case BoundDeclarationPattern { IsVar: false }: case BoundConstantPattern { ConstantValue: { IsNull: false } }: return false; case BoundConstantPattern { ConstantValue: { IsNull: true } }: return true; case BoundNegatedPattern negated: return !patternMatchesNull(negated.Negated); case BoundBinaryPattern binary: if (binary.Disjunction) { // `a?.b(out x) is null or C` // pattern matches null if either subpattern matches null var leftNullTest = patternMatchesNull(binary.Left); return patternMatchesNull(binary.Left) || patternMatchesNull(binary.Right); } // `a?.b out x is not null and var c` // pattern matches null only if both subpatterns match null return patternMatchesNull(binary.Left) && patternMatchesNull(binary.Right); case BoundDeclarationPattern { IsVar: true }: case BoundDiscardPattern: return true; default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } // Returns `true` if the pattern only matches a `true` input. // Returns `false` if the pattern only matches a `false` input. // Otherwise, returns `null`. static bool? isBoolTest(BoundPattern pattern) { switch (pattern) { case BoundConstantPattern { ConstantValue: { IsBoolean: true, BooleanValue: var boolValue } }: return boolValue; case BoundNegatedPattern negated: return !isBoolTest(negated.Negated); case BoundBinaryPattern binary: if (binary.Disjunction) { // `(a != null && a.b(out x)) is true or true` matches `true` // `(a != null && a.b(out x)) is true or false` matches any boolean // both subpatterns must have the same bool test for the test to propagate out var leftNullTest = isBoolTest(binary.Left); return leftNullTest is null ? null : leftNullTest != isBoolTest(binary.Right) ? null : leftNullTest; } // `(a != null && a.b(out x)) is true and true` matches `true` // `(a != null && a.b(out x)) is true and var x` matches `true` // `(a != null && a.b(out x)) is true and false` never matches and is a compile error return isBoolTest(binary.Left) ?? isBoolTest(binary.Right); case BoundConstantPattern { ConstantValue: { IsBoolean: false } }: case BoundDiscardPattern: case BoundTypePattern: case BoundRecursivePattern: case BoundITuplePattern: case BoundRelationalPattern: case BoundDeclarationPattern: return null; default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } } public virtual void VisitPattern(BoundPattern pattern) { Split(); } public override BoundNode VisitConstantPattern(BoundConstantPattern node) { // All patterns are handled by VisitPattern throw ExceptionUtilities.Unreachable; } public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { return VisitTupleExpression(node); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { return VisitTupleExpression(node); } private BoundNode VisitTupleExpression(BoundTupleExpression node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), null); return null; } public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { VisitRvalue(node.Left); VisitRvalue(node.Right); return null; } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { VisitRvalue(node.Receiver); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { VisitRvalue(node.Receiver); return null; } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { VisitRvalue(node.Expression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } #nullable enable protected BoundNode? VisitInterpolatedStringBase(BoundInterpolatedStringBase node, InterpolatedStringHandlerData? data) { // If there can be any branching, then we need to treat the expressions // as optionally evaluated. Otherwise, we treat them as always evaluated (BoundExpression? construction, bool useBoolReturns, bool firstPartIsConditional) = data switch { null => (null, false, false), { } d => (d.Construction, d.UsesBoolReturns, d.HasTrailingHandlerValidityParameter) }; VisitRvalue(construction); bool hasConditionalEvaluation = useBoolReturns || firstPartIsConditional; TLocalState? shortCircuitState = hasConditionalEvaluation ? State.Clone() : default; _ = VisitInterpolatedStringHandlerParts(node, useBoolReturns, firstPartIsConditional, ref shortCircuitState); if (hasConditionalEvaluation) { Debug.Assert(shortCircuitState != null); Join(ref this.State, ref shortCircuitState); } return null; } #nullable disable public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { return VisitInterpolatedStringBase(node, node.InterpolationData); } public override BoundNode VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // If the node is unconverted, we'll just treat it as if the contents are always evaluated return VisitInterpolatedStringBase(node, data: null); } public override BoundNode VisitStringInsert(BoundStringInsert node) { VisitRvalue(node.Value); if (node.Alignment != null) { VisitRvalue(node.Alignment); } if (node.Format != null) { VisitRvalue(node.Format); } return null; } public override BoundNode VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { return null; } public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { return null; } public override BoundNode VisitArgList(BoundArgList node) { // The "__arglist" expression that is legal inside a varargs method has no // effect on flow analysis and it has no children. return null; } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { // When we have M(__arglist(x, y, z)) we must visit x, y and z. VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { // Note that we require that the variable whose reference we are taking // has been initialized; it is similar to passing the variable as a ref parameter. VisitRvalue(node.Operand, isKnownToBeAnLvalue: true); return null; } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) { VisitStatement(node.Statement); return null; } public override BoundNode VisitLambda(BoundLambda node) => null; public override BoundNode VisitLocal(BoundLocal node) { SplitIfBooleanConstant(node); return null; } public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node) { if (node.InitializerOpt != null) { // analyze the expression VisitRvalue(node.InitializerOpt, isKnownToBeAnLvalue: node.LocalSymbol.RefKind != RefKind.None); // byref assignment is also a potential write if (node.LocalSymbol.RefKind != RefKind.None) { WriteArgument(node.InitializerOpt, node.LocalSymbol.RefKind, method: null); } } return null; } public override BoundNode VisitBlock(BoundBlock node) { VisitStatements(node.Statements); return null; } private void VisitStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { VisitStatement(statement); } } public override BoundNode VisitScope(BoundScope node) { VisitStatements(node.Statements); return null; } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitCall(BoundCall node) { // If the method being called is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // definite assignment analysis. bool callsAreOmitted = node.Method.CallsAreOmitted(node.SyntaxTree); TLocalState savedState = default(TLocalState); if (callsAreOmitted) { savedState = this.State.Clone(); SetUnreachable(); } VisitReceiverBeforeCall(node.ReceiverOpt, node.Method); VisitArgumentsBeforeCall(node.Arguments, node.ArgumentRefKindsOpt); if (node.Method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: true); } VisitArgumentsAfterCall(node.Arguments, node.ArgumentRefKindsOpt, node.Method); VisitReceiverAfterCall(node.ReceiverOpt, node.Method); if (callsAreOmitted) { this.State = savedState; } return null; } protected void VisitLocalFunctionUse(LocalFunctionSymbol symbol, SyntaxNode syntax, bool isCall) { var localFuncState = GetOrCreateLocalFuncUsages(symbol); VisitLocalFunctionUse(symbol, localFuncState, syntax, isCall); } protected virtual void VisitLocalFunctionUse( LocalFunctionSymbol symbol, TLocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { if (isCall) { Join(ref State, ref localFunctionState.StateFromBottom); Meet(ref State, ref localFunctionState.StateFromTop); } localFunctionState.Visited = true; } private void VisitReceiverBeforeCall(BoundExpression receiverOpt, MethodSymbol method) { if (method is null || method.MethodKind != MethodKind.Constructor) { VisitRvalue(receiverOpt); } } private void VisitReceiverAfterCall(BoundExpression receiverOpt, MethodSymbol method) { if (receiverOpt is null) { return; } if (method is null) { WriteArgument(receiverOpt, RefKind.Ref, method: null); } else if (method.TryGetThisParameter(out var thisParameter) && thisParameter is object && !TypeIsImmutable(thisParameter.Type)) { var thisRefKind = thisParameter.RefKind; if (thisRefKind.IsWritableReference()) { WriteArgument(receiverOpt, thisRefKind, method); } } } /// <summary> /// Certain (struct) types are known by the compiler to be immutable. In these cases calling a method on /// the type is known (by flow analysis) not to write the receiver. /// </summary> /// <param name="t"></param> /// <returns></returns> private static bool TypeIsImmutable(TypeSymbol t) { switch (t.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_DateTime: return true; default: return t.IsNullableType(); } } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { var method = GetReadMethod(node.Indexer); VisitReceiverBeforeCall(node.ReceiverOpt, method); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); if ((object)method != null) { VisitReceiverAfterCall(node.ReceiverOpt, method); } return null; } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { // Index or Range pattern indexers evaluate the following in order: // 1. The receiver // 1. The Count or Length method off the receiver // 2. The argument to the access // 3. The pattern method VisitRvalue(node.Receiver); var method = GetReadMethod(node.LengthOrCountProperty); VisitReceiverAfterCall(node.Receiver, method); VisitRvalue(node.Argument); method = node.PatternSymbol switch { PropertySymbol p => GetReadMethod(p), MethodSymbol m => m, _ => throw ExceptionUtilities.UnexpectedValue(node.PatternSymbol) }; VisitReceiverAfterCall(node.Receiver, method); return null; } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { VisitRvalue(node.ReceiverOpt); VisitRvalue(node.Argument); return null; } /// <summary> /// Do not call for a local function. /// </summary> protected virtual void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { Debug.Assert(method?.OriginalDefinition.MethodKind != MethodKind.LocalFunction); VisitArgumentsBeforeCall(arguments, refKindsOpt); VisitArgumentsAfterCall(arguments, refKindsOpt, method); } private void VisitArgumentsBeforeCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { // first value and ref parameters are read... for (int i = 0; i < arguments.Length; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); if (refKind != RefKind.Out) { VisitRvalue(arguments[i], isKnownToBeAnLvalue: refKind != RefKind.None); } else { VisitLvalue(arguments[i]); } } } /// <summary> /// Writes ref and out parameters /// </summary> private void VisitArgumentsAfterCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { for (int i = 0; i < arguments.Length; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); // passing as a byref argument is also a potential write if (refKind != RefKind.None) { WriteArgument(arguments[i], refKind, method); } } } protected static RefKind GetRefKind(ImmutableArray<RefKind> refKindsOpt, int index) { return refKindsOpt.IsDefault || refKindsOpt.Length <= index ? RefKind.None : refKindsOpt[index]; } protected virtual void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method) { } public override BoundNode VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { VisitRvalue(child as BoundExpression); } return null; } public override BoundNode VisitBadStatement(BoundBadStatement node) { foreach (var child in node.ChildBoundNodes) { if (child is BoundStatement) { VisitStatement(child as BoundStatement); } else { VisitRvalue(child as BoundExpression); } } return null; } // Can be called as part of a bad expression. public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) { foreach (var child in node.Initializers) { VisitRvalue(child); } return null; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { var methodGroup = node.Argument as BoundMethodGroup; if (methodGroup != null) { if ((object)node.MethodOpt != null && node.MethodOpt.RequiresInstanceReceiver) { EnterRegionIfNeeded(methodGroup); VisitRvalue(methodGroup.ReceiverOpt); LeaveRegionIfNeeded(methodGroup); } else if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false); } } else { VisitRvalue(node.Argument); } return null; } public override BoundNode VisitTypeExpression(BoundTypeExpression node) { return null; } public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // If we're seeing a node of this kind, then we failed to resolve the member access // as either a type or a property/field/event/local/parameter. In such cases, // the second interpretation applies so just visit the node for that. return this.Visit(node.Data.ValueExpression); } public override BoundNode VisitLiteral(BoundLiteral node) { SplitIfBooleanConstant(node); return null; } protected void SplitIfBooleanConstant(BoundExpression node) { if (node.ConstantValue is { IsBoolean: true, BooleanValue: bool booleanValue }) { var unreachable = UnreachableState(); Split(); if (booleanValue) { StateWhenFalse = unreachable; } else { StateWhenTrue = unreachable; } } } public override BoundNode VisitMethodDefIndex(BoundMethodDefIndex node) { return null; } public override BoundNode VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) { return null; } public override BoundNode VisitModuleVersionId(BoundModuleVersionId node) { return null; } public override BoundNode VisitModuleVersionIdString(BoundModuleVersionIdString node) { return null; } public override BoundNode VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) { return null; } public override BoundNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node) { return null; } public override BoundNode VisitConversion(BoundConversion node) { if (node.ConversionKind == ConversionKind.MethodGroup) { if (node.IsExtensionMethod || ((object)node.SymbolOpt != null && node.SymbolOpt.RequiresInstanceReceiver)) { BoundExpression receiver = ((BoundMethodGroup)node.Operand).ReceiverOpt; // A method group's "implicit this" is only used for instance methods. EnterRegionIfNeeded(node.Operand); VisitRvalue(receiver); LeaveRegionIfNeeded(node.Operand); } else if (node.SymbolOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false); } } else { Visit(node.Operand); } return null; } public override BoundNode VisitIfStatement(BoundIfStatement node) { // 5.3.3.5 If statements VisitCondition(node.Condition); TLocalState trueState = StateWhenTrue; TLocalState falseState = StateWhenFalse; SetState(trueState); VisitStatement(node.Consequence); trueState = this.State; SetState(falseState); if (node.AlternativeOpt != null) { VisitStatement(node.AlternativeOpt); } Join(ref this.State, ref trueState); return null; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var oldPending = SavePending(); // we do not allow branches into a try statement var initialState = this.State.Clone(); // use this state to resolve all the branches introduced and internal to try/catch var pendingBeforeTry = SavePending(); VisitTryBlockWithAnyTransferFunction(node.TryBlock, node, ref initialState); var finallyState = initialState.Clone(); var endState = this.State; foreach (var catchBlock in node.CatchBlocks) { SetState(initialState.Clone()); VisitCatchBlockWithAnyTransferFunction(catchBlock, ref finallyState); Join(ref endState, ref this.State); } // Give a chance to branches internal to try/catch to resolve. // Carry forward unresolved branches. RestorePending(pendingBeforeTry); // NOTE: At this point all branches that are internal to try or catch blocks have been resolved. // However we have not yet restored the oldPending branches. Therefore all the branches // that are currently pending must have been introduced in try/catch and do not terminate inside those blocks. // // With exception of YieldReturn, these branches logically go through finally, if such present, // so we must Union/Intersect finally state as appropriate if (node.FinallyBlockOpt != null) { // branches from the finally block, while illegal, should still not be considered // to execute the finally block before occurring. Also, we do not handle branches // *into* the finally block. SetState(finallyState); // capture tryAndCatchPending before going into finally // we will need pending branches as they were before finally later var tryAndCatchPending = SavePending(); var stateMovedUpInFinally = ReachableBottomState(); VisitFinallyBlockWithAnyTransferFunction(node.FinallyBlockOpt, ref stateMovedUpInFinally); foreach (var pend in tryAndCatchPending.PendingBranches) { if (pend.Branch == null) { continue; // a tracked exception } if (pend.Branch.Kind != BoundKind.YieldReturnStatement) { updatePendingBranchState(ref pend.State, ref stateMovedUpInFinally); if (pend.IsConditionalState) { updatePendingBranchState(ref pend.StateWhenTrue, ref stateMovedUpInFinally); updatePendingBranchState(ref pend.StateWhenFalse, ref stateMovedUpInFinally); } } } RestorePending(tryAndCatchPending); Meet(ref endState, ref this.State); if (_nonMonotonicTransfer) { Join(ref endState, ref stateMovedUpInFinally); } } SetState(endState); RestorePending(oldPending); return null; void updatePendingBranchState(ref TLocalState stateToUpdate, ref TLocalState stateMovedUpInFinally) { Meet(ref stateToUpdate, ref this.State); if (_nonMonotonicTransfer) { Join(ref stateToUpdate, ref stateMovedUpInFinally); } } } protected Optional<TLocalState> NonMonotonicState; /// <summary> /// Join state from other try block, potentially in a nested method. /// </summary> protected virtual void JoinTryBlockState(ref TLocalState self, ref TLocalState other) { Join(ref self, ref other); } private void VisitTryBlockWithAnyTransferFunction(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitTryBlock(tryBlock, node, ref tryState); var tempTryStateValue = NonMonotonicState.Value; Join(ref tryState, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitTryBlock(tryBlock, node, ref tryState); } } protected virtual void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) { VisitStatement(tryBlock); } private void VisitCatchBlockWithAnyTransferFunction(BoundCatchBlock catchBlock, ref TLocalState finallyState) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitCatchBlock(catchBlock, ref finallyState); var tempTryStateValue = NonMonotonicState.Value; Join(ref finallyState, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitCatchBlock(catchBlock, ref finallyState); } } protected virtual void VisitCatchBlock(BoundCatchBlock catchBlock, ref TLocalState finallyState) { if (catchBlock.ExceptionSourceOpt != null) { VisitLvalue(catchBlock.ExceptionSourceOpt); } if (catchBlock.ExceptionFilterPrologueOpt is { }) { VisitStatementList(catchBlock.ExceptionFilterPrologueOpt); } if (catchBlock.ExceptionFilterOpt != null) { VisitCondition(catchBlock.ExceptionFilterOpt); SetState(StateWhenTrue); } VisitStatement(catchBlock.Body); } private void VisitFinallyBlockWithAnyTransferFunction(BoundStatement finallyBlock, ref TLocalState stateMovedUp) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitFinallyBlock(finallyBlock, ref stateMovedUp); var tempTryStateValue = NonMonotonicState.Value; Join(ref stateMovedUp, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitFinallyBlock(finallyBlock, ref stateMovedUp); } } protected virtual void VisitFinallyBlock(BoundStatement finallyBlock, ref TLocalState stateMovedUp) { VisitStatement(finallyBlock); // this should generate no pending branches } public override BoundNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node) { return VisitBlock(node.FinallyBlock); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { var result = VisitReturnStatementNoAdjust(node); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return result; } protected virtual BoundNode VisitReturnStatementNoAdjust(BoundReturnStatement node) { VisitRvalue(node.ExpressionOpt, isKnownToBeAnLvalue: node.RefKind != RefKind.None); // byref return is also a potential write if (node.RefKind != RefKind.None) { WriteArgument(node.ExpressionOpt, node.RefKind, method: null); } return null; } public override BoundNode VisitThisReference(BoundThisReference node) { return null; } public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { return null; } public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { return null; } public override BoundNode VisitParameter(BoundParameter node) { return null; } protected virtual void VisitLvalueParameter(BoundParameter node) { } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Constructor); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNewT(BoundNewT node) { VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { VisitRvalue(node.InitializerExpressionOpt); return null; } // represents anything that occurs at the invocation of the property setter protected virtual void PropertySetter(BoundExpression node, BoundExpression receiver, MethodSymbol setter, BoundExpression value = null) { VisitReceiverAfterCall(receiver, setter); } // returns false if expression is not a property access // or if the property has a backing field // and accessed in a corresponding constructor private bool RegularPropertyAccess(BoundExpression expr) { if (expr.Kind != BoundKind.PropertyAccess) { return false; } return !Binder.AccessingAutoPropertyFromConstructor((BoundPropertyAccess)expr, _symbol); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var method = GetWriteMethod(property); VisitReceiverBeforeCall(left.ReceiverOpt, method); VisitRvalue(node.Right); PropertySetter(node, left.ReceiverOpt, method, node.Right); return null; } } VisitLvalue(node.Left); VisitRvalue(node.Right, isKnownToBeAnLvalue: node.IsRef); // byref assignment is also a potential write if (node.IsRef) { // Assume that BadExpression is a ref location to avoid // cascading diagnostics var refKind = node.Left.Kind == BoundKind.BadExpression ? RefKind.Ref : node.Left.GetRefKind(); WriteArgument(node.Right, refKind, method: null); } return null; } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { VisitLvalue(node.Left); VisitRvalue(node.Right); return null; } public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) { // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { VisitCompoundAssignmentTarget(node); VisitRvalue(node.Right); AfterRightHasBeenVisited(node); return null; } protected void VisitCompoundAssignmentTarget(BoundCompoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var readMethod = GetReadMethod(property); Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)GetWriteMethod(property)); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); return; } } VisitRvalue(node.Left, isKnownToBeAnLvalue: true); } protected void AfterRightHasBeenVisited(BoundCompoundAssignmentOperator node) { if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var writeMethod = GetWriteMethod(property); PropertySetter(node, left.ReceiverOpt, writeMethod); VisitReceiverAfterCall(left.ReceiverOpt, writeMethod); return; } } } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); return null; } private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol) { bool asLvalue = (object)fieldSymbol != null && (fieldSymbol.IsFixedSizeBuffer || !fieldSymbol.IsStatic && fieldSymbol.ContainingType.TypeKind == TypeKind.Struct && receiverOpt != null && receiverOpt.Kind != BoundKind.TypeExpression && (object)receiverOpt.Type != null && !receiverOpt.Type.IsPrimitiveRecursiveStruct()); if (asLvalue) { VisitLvalue(receiverOpt); } else { VisitRvalue(receiverOpt); } } public override BoundNode VisitFieldInfo(BoundFieldInfo node) { return null; } public override BoundNode VisitMethodInfo(BoundMethodInfo node) { return null; } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; if (Binder.AccessingAutoPropertyFromConstructor(node, _symbol)) { var backingField = (property as SourcePropertySymbolBase)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(node.ReceiverOpt, backingField); return null; } } var method = GetReadMethod(property); VisitReceiverBeforeCall(node.ReceiverOpt, method); VisitReceiverAfterCall(node.ReceiverOpt, method); return null; // TODO: In an expression such as // M().Prop = G(); // Exceptions thrown from M() occur before those from G(), but exceptions from the property accessor // occur after both. The precise abstract flow pass does not yet currently have this quite right. // Probably what is needed is a VisitPropertyAccessInternal(BoundPropertyAccess node, bool read) // which should assume that the receiver will have been handled by the caller. This can be invoked // twice for read/write operations such as // M().Prop += 1 // or at the appropriate place in the sequence for read or write operations. // Do events require any special handling too? } public override BoundNode VisitEventAccess(BoundEventAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.EventSymbol.AssociatedField); return null; } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return null; } public override BoundNode VisitQueryClause(BoundQueryClause node) { VisitRvalue(node.UnoptimizedForm ?? node.Value); return null; } private BoundNode VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) { foreach (var v in node.LocalDeclarations) { Visit(v); } return null; } public override BoundNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode VisitWhileStatement(BoundWhileStatement node) { // while (node.Condition) { node.Body; node.ContinueLabel: } node.BreakLabel: LoopHead(node); VisitCondition(node.Condition); TLocalState bodyState = StateWhenTrue; TLocalState breakState = StateWhenFalse; SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitWithExpression(BoundWithExpression node) { VisitRvalue(node.Receiver); VisitObjectOrCollectionInitializerExpression(node.InitializerExpression.Initializers); return null; } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { VisitRvalue(node.Expression); foreach (var i in node.Indices) { VisitRvalue(i); } return null; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { if (node.OperatorKind.IsLogical()) { Debug.Assert(!node.OperatorKind.IsUserDefined()); VisitBinaryLogicalOperatorChildren(node); } else if (node.InterpolatedStringHandlerData is { } data) { VisitBinaryInterpolatedStringAddition(node); } else { VisitBinaryOperatorChildren(node); } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { VisitBinaryLogicalOperatorChildren(node); return null; } private void VisitBinaryLogicalOperatorChildren(BoundExpression node) { // Do not blow the stack due to a deep recursion on the left. var stack = ArrayBuilder<BoundExpression>.GetInstance(); BoundExpression binary; BoundExpression child = node; while (true) { var childKind = child.Kind; if (childKind == BoundKind.BinaryOperator) { var binOp = (BoundBinaryOperator)child; if (!binOp.OperatorKind.IsLogical()) { break; } Debug.Assert(!binOp.OperatorKind.IsUserDefined()); binary = child; child = binOp.Left; } else if (childKind == BoundKind.UserDefinedConditionalLogicalOperator) { binary = child; child = ((BoundUserDefinedConditionalLogicalOperator)binary).Left; } else { break; } stack.Push(binary); } Debug.Assert(stack.Count > 0); VisitCondition(child); while (true) { binary = stack.Pop(); BinaryOperatorKind kind; BoundExpression right; switch (binary.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)binary; kind = binOp.OperatorKind; right = binOp.Right; break; case BoundKind.UserDefinedConditionalLogicalOperator: var udBinOp = (BoundUserDefinedConditionalLogicalOperator)binary; kind = udBinOp.OperatorKind; right = udBinOp.Right; break; default: throw ExceptionUtilities.UnexpectedValue(binary.Kind); } var op = kind.Operator(); var isAnd = op == BinaryOperatorKind.And; var isBool = kind.OperandTypes() == BinaryOperatorKind.Bool; Debug.Assert(isAnd || op == BinaryOperatorKind.Or); var leftTrue = this.StateWhenTrue; var leftFalse = this.StateWhenFalse; SetState(isAnd ? leftTrue : leftFalse); AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse); if (stack.Count == 0) { break; } AdjustConditionalState(binary); } Debug.Assert((object)binary == node); stack.Free(); } protected virtual void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) { Visit(right); // First part of VisitCondition AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse); } protected void AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) { AdjustConditionalState(right); // Second part of VisitCondition if (!isBool) { this.Unsplit(); this.Split(); } var resultTrue = this.StateWhenTrue; var resultFalse = this.StateWhenFalse; if (isAnd) { Join(ref resultFalse, ref leftFalse); } else { Join(ref resultTrue, ref leftTrue); } SetConditionalState(resultTrue, resultFalse); if (!isBool) { this.Unsplit(); } } private void VisitBinaryOperatorChildren(BoundBinaryOperator node) { // It is common in machine-generated code for there to be deep recursion on the left side of a binary // operator, for example, if you have "a + b + c + ... " then the bound tree will be deep on the left // hand side. To mitigate the risk of stack overflow we use an explicit stack. // // Of course we must ensure that we visit the left hand side before the right hand side. var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); BoundBinaryOperator binary = node; do { stack.Push(binary); binary = binary.Left as BoundBinaryOperator; } while (binary != null && !binary.OperatorKind.IsLogical() && binary.InterpolatedStringHandlerData is null); VisitBinaryOperatorChildren(stack); stack.Free(); } #nullable enable protected virtual void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(binary.Left, out var stateWhenNotNull) && canLearnFromOperator(binary) && isKnownNullOrNotNull(binary.Right)) { if (_nonMonotonicTransfer) { // In this very specific scenario, we need to do extra work to track unassignments for region analysis. // See `AbstractFlowPass.VisitCatchBlockWithAnyTransferFunction` for a similar scenario in catch blocks. Optional<TLocalState> oldState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitRvalue(binary.Right); var tempStateValue = NonMonotonicState.Value; Join(ref stateWhenNotNull, ref tempStateValue); if (oldState.HasValue) { var oldStateValue = oldState.Value; Join(ref oldStateValue, ref tempStateValue); oldState = oldStateValue; } NonMonotonicState = oldState; } else { VisitRvalue(binary.Right); Meet(ref stateWhenNotNull, ref State); } var isNullConstant = binary.Right.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); if (stack.Count == 0) { return; } binary = stack.Pop(); } while (true) { if (!canLearnFromOperator(binary) || !learnFromOperator(binary)) { Unsplit(); VisitRvalue(binary.Right); } if (stack.Count == 0) { break; } binary = stack.Pop(); } static bool canLearnFromOperator(BoundBinaryOperator binary) { var kind = binary.OperatorKind; return kind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual && (!kind.IsUserDefined() || kind.IsLifted()); } static bool isKnownNullOrNotNull(BoundExpression expr) { return expr.ConstantValue is object || (expr is BoundConversion { ConversionKind: ConversionKind.ExplicitNullable or ConversionKind.ImplicitNullable } conv && conv.Operand.Type!.IsNonNullableValueType()); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; // Returns true if `binary.Right` was visited by the call. bool learnFromOperator(BoundBinaryOperator binary) { // `true == a?.b(out x)` if (isKnownNullOrNotNull(binary.Left) && TryVisitConditionalAccess(binary.Right, out var stateWhenNotNull)) { var isNullConstant = binary.Left.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // `a && b(out x) == true` else if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); return true; } // `true == a && b(out x)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } return true; } return false; } } protected void VisitBinaryInterpolatedStringAddition(BoundBinaryOperator node) { Debug.Assert(node.InterpolatedStringHandlerData.HasValue); var parts = ArrayBuilder<BoundInterpolatedString>.GetInstance(); var data = node.InterpolatedStringHandlerData.GetValueOrDefault(); node.VisitBinaryOperatorInterpolatedString( (parts, @this: this), stringCallback: static (BoundInterpolatedString interpolatedString, (ArrayBuilder<BoundInterpolatedString> parts, AbstractFlowPass<TLocalState, TLocalFunctionState> @this) arg) => { arg.parts.Add(interpolatedString); return true; }, binaryOperatorCallback: (op, arg) => [email protected](op)); Debug.Assert(parts.Count >= 2); VisitRvalue(data.Construction); bool visitedFirst = false; bool hasTrailingHandlerValidityParameter = data.HasTrailingHandlerValidityParameter; bool hasConditionalEvaluation = data.UsesBoolReturns || hasTrailingHandlerValidityParameter; TLocalState? shortCircuitState = hasConditionalEvaluation ? State.Clone() : default; foreach (var part in parts) { visitedFirst |= VisitInterpolatedStringHandlerParts(part, data.UsesBoolReturns, firstPartIsConditional: visitedFirst || hasTrailingHandlerValidityParameter, ref shortCircuitState); } if (hasConditionalEvaluation) { Join(ref State, ref shortCircuitState); } parts.Free(); } protected virtual void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) { } protected virtual bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref TLocalState? shortCircuitState) { Debug.Assert(shortCircuitState != null || (!usesBoolReturns && !firstPartIsConditional)); if (node.Parts.IsEmpty) { return false; } ReadOnlySpan<BoundExpression> parts; if (firstPartIsConditional) { parts = node.Parts.AsSpan(); } else { VisitRvalue(node.Parts[0]); shortCircuitState = State.Clone(); parts = node.Parts.AsSpan()[1..]; } foreach (var part in parts) { VisitRvalue(part); if (usesBoolReturns) { Debug.Assert(shortCircuitState != null); Join(ref shortCircuitState, ref State); } } return true; } #nullable disable public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { if (node.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { // We have a special case for the ! unary operator, which can operate in a boolean context (5.3.3.26) VisitCondition(node.Operand); // it inverts the sense of assignedWhenTrue and assignedWhenFalse. SetConditionalState(StateWhenFalse, StateWhenTrue); } else { VisitRvalue(node.Operand); } return null; } public override BoundNode VisitRangeExpression(BoundRangeExpression node) { if (node.LeftOperandOpt != null) { VisitRvalue(node.LeftOperandOpt); } if (node.RightOperandOpt != null) { VisitRvalue(node.RightOperandOpt); } return null; } public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { VisitRvalue(node.Expression); PendingBranches.Add(new PendingBranch(node, this.State, null)); return null; } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { // TODO: should we also specially handle events? if (RegularPropertyAccess(node.Operand)) { var left = (BoundPropertyAccess)node.Operand; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var readMethod = GetReadMethod(property); var writeMethod = GetWriteMethod(property); Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)writeMethod); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); PropertySetter(node, left.ReceiverOpt, writeMethod); // followed by a write return null; } } VisitRvalue(node.Operand); return null; } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } if (node.InitializerOpt != null) { VisitArrayInitializationInternal(node, node.InitializerOpt); } return null; } private void VisitArrayInitializationInternal(BoundArrayCreation arrayCreation, BoundArrayInitialization node) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { VisitArrayInitializationInternal(arrayCreation, (BoundArrayInitialization)child); } else { VisitRvalue(child); } } } public override BoundNode VisitForStatement(BoundForStatement node) { if (node.Initializer != null) { VisitStatement(node.Initializer); } LoopHead(node); TLocalState bodyState, breakState; if (node.Condition != null) { VisitCondition(node.Condition); bodyState = this.StateWhenTrue; breakState = this.StateWhenFalse; } else { bodyState = this.State; breakState = UnreachableState(); } SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); if (node.Increment != null) { VisitStatement(node.Increment); } LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitForEachStatement(BoundForEachStatement node) { // foreach [await] ( var v in node.Expression ) { node.Body; node.ContinueLabel: } node.BreakLabel: VisitForEachExpression(node); var breakState = this.State.Clone(); LoopHead(node); VisitForEachIterationVariables(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); if (AwaitUsingAndForeachAddsPendingBranch && ((CommonForEachStatementSyntax)node.Syntax).AwaitKeyword != default) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return null; } protected virtual void VisitForEachExpression(BoundForEachStatement node) { VisitRvalue(node.Expression); } public virtual void VisitForEachIterationVariables(BoundForEachStatement node) { } public override BoundNode VisitAsOperator(BoundAsOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitIsOperator(BoundIsOperator node) { if (VisitPossibleConditionalAccess(node.Operand, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); SetConditionalState(stateWhenNotNull, State); } else { // `(a && b.M(out x)) is bool` should discard conditional state from LHS Unsplit(); } return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { if (node.ReceiverOpt != null) { // An explicit or implicit receiver, for example in an expression such as (x.Goo is Action, or Goo is Action), is considered to be read. VisitRvalue(node.ReceiverOpt); } return null; } #nullable enable public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { if (IsConstantNull(node.LeftOperand)) { VisitRvalue(node.LeftOperand); Visit(node.RightOperand); } else { TLocalState savedState; if (VisitPossibleConditionalAccess(node.LeftOperand, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); savedState = stateWhenNotNull; } else { Unsplit(); savedState = State.Clone(); } if (node.LeftOperand.ConstantValue != null) { SetUnreachable(); } Visit(node.RightOperand); if (IsConditionalState) { Join(ref StateWhenTrue, ref savedState); Join(ref StateWhenFalse, ref savedState); } else { Join(ref this.State, ref savedState); } } return null; } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) { var access = node switch { BoundConditionalAccess ca => ca, BoundConversion { Conversion: Conversion conversion, Operand: BoundConditionalAccess ca } when CanPropagateStateWhenNotNull(conversion) => ca, _ => null }; if (access is not null) { EnterRegionIfNeeded(access); Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); Debug.Assert(!IsConditionalState); LeaveRegionIfNeeded(access); return true; } stateWhenNotNull = default; return false; } /// <summary> /// "State when not null" can only propagate out of a conditional access if /// it is not subject to a user-defined conversion whose parameter is not of a non-nullable value type. /// </summary> protected static bool CanPropagateStateWhenNotNull(Conversion conversion) { if (!conversion.IsValid) { return false; } if (!conversion.IsUserDefined) { return true; } var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount is 1); var param = method.Parameters[0]; return param.Type.IsNonNullableValueType(); } /// <summary> /// Unconditionally visits an expression. /// If the expression has "state when not null" after visiting, /// the method returns 'true' and writes the state to <paramref name="stateWhenNotNull" />. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } else { Visit(node); return false; } } private void VisitConditionalAccess(BoundConditionalAccess node, out TLocalState stateWhenNotNull) { // The receiver may also be a conditional access. // `(a?.b(x = 1))?.c(y = 1)` if (VisitPossibleConditionalAccess(node.Receiver, out var receiverStateWhenNotNull)) { stateWhenNotNull = receiverStateWhenNotNull; } else { Unsplit(); stateWhenNotNull = this.State.Clone(); } if (node.Receiver.ConstantValue != null && !IsConstantNull(node.Receiver)) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull if (VisitPossibleConditionalAccess(node.AccessExpression, out var firstAccessStateWhenNotNull)) { stateWhenNotNull = firstAccessStateWhenNotNull; } else { Unsplit(); stateWhenNotNull = this.State.Clone(); } } else { var savedState = this.State.Clone(); if (IsConstantNull(node.Receiver)) { SetUnreachable(); } else { SetState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. VisitRvalue(innerCondAccess.Receiver); expr = innerCondAccess.AccessExpression; // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); } Debug.Assert(expr is BoundExpression); VisitRvalue(expr); stateWhenNotNull = State; State = savedState; Join(ref State, ref stateWhenNotNull); } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, stateWhenNotNull: out _); return null; } #nullable disable public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) { VisitRvalue(node.Receiver); var savedState = this.State.Clone(); VisitRvalue(node.WhenNotNull); Join(ref this.State, ref savedState); if (node.WhenNullOpt != null) { savedState = this.State.Clone(); VisitRvalue(node.WhenNullOpt); Join(ref this.State, ref savedState); } return null; } public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) { return null; } public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) { var savedState = this.State.Clone(); VisitRvalue(node.ValueTypeReceiver); Join(ref this.State, ref savedState); savedState = this.State.Clone(); VisitRvalue(node.ReferenceTypeReceiver); Join(ref this.State, ref savedState); return null; } public override BoundNode VisitSequence(BoundSequence node) { var sideEffects = node.SideEffects; if (!sideEffects.IsEmpty) { foreach (var se in sideEffects) { VisitRvalue(se); } } VisitRvalue(node.Value); return null; } public override BoundNode VisitSequencePoint(BoundSequencePoint node) { if (node.StatementOpt != null) { VisitStatement(node.StatementOpt); } return null; } public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node) { if (node.StatementOpt != null) { VisitStatement(node.StatementOpt); } return null; } public override BoundNode VisitStatementList(BoundStatementList node) { return VisitStatementListWorker(node); } private BoundNode VisitStatementListWorker(BoundStatementList node) { foreach (var statement in node.Statements) { VisitStatement(statement); } return null; } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { return VisitStatementListWorker(node); } public override BoundNode VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. return VisitLambda(node.BindForErrorRecovery()); } public override BoundNode VisitBreakStatement(BoundBreakStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } public override BoundNode VisitContinueStatement(BoundContinueStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } public override BoundNode VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) { return VisitConditionalOperatorCore(node, isByRef: false, node.Condition, node.Consequence, node.Alternative); } public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { return VisitConditionalOperatorCore(node, node.IsRef, node.Condition, node.Consequence, node.Alternative); } #nullable enable protected virtual BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isByRef, BoundExpression condition, BoundExpression consequence, BoundExpression alternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; if (IsConstantTrue(condition)) { VisitConditionalOperand(alternativeState, alternative, isByRef); VisitConditionalOperand(consequenceState, consequence, isByRef); } else if (IsConstantFalse(condition)) { VisitConditionalOperand(consequenceState, consequence, isByRef); VisitConditionalOperand(alternativeState, alternative, isByRef); } else { // at this point, the state is conditional after a conditional expression if: // 1. the state is conditional after the consequence, or // 2. the state is conditional after the alternative VisitConditionalOperand(consequenceState, consequence, isByRef); var conditionalAfterConsequence = IsConditionalState; var (afterConsequenceWhenTrue, afterConsequenceWhenFalse) = conditionalAfterConsequence ? (StateWhenTrue, StateWhenFalse) : (State, State); VisitConditionalOperand(alternativeState, alternative, isByRef); if (!conditionalAfterConsequence && !IsConditionalState) { // simplify in the common case Join(ref this.State, ref afterConsequenceWhenTrue); } else { Split(); Join(ref this.StateWhenTrue, ref afterConsequenceWhenTrue); Join(ref this.StateWhenFalse, ref afterConsequenceWhenFalse); } } return null; } #nullable disable private void VisitConditionalOperand(TLocalState state, BoundExpression operand, bool isByRef) { SetState(state); if (isByRef) { VisitLvalue(operand); // exposing ref is a potential write WriteArgument(operand, RefKind.Ref, method: null); } else { Visit(operand); } } public override BoundNode VisitBaseReference(BoundBaseReference node) { return null; } public override BoundNode VisitDoStatement(BoundDoStatement node) { // do { statements; node.ContinueLabel: } while (node.Condition) node.BreakLabel: LoopHead(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); VisitCondition(node.Condition); TLocalState breakState = this.StateWhenFalse; SetState(this.StateWhenTrue); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } protected void VisitLabel(LabelSymbol label, BoundStatement node) { node.AssertIsLabeledStatementWithLabel(label); ResolveBranches(label, node); var state = LabelState(label); Join(ref this.State, ref state); _labels[label] = this.State.Clone(); _labelsSeen.Add(node); } protected virtual void VisitLabel(BoundLabeledStatement node) { VisitLabel(node.Label, node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { VisitLabel(node.Label, node); return null; } public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) { VisitLabel(node); VisitStatement(node.Body); return null; } public override BoundNode VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode VisitNoOpStatement(BoundNoOpStatement node) { return null; } public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node) { return null; } public override BoundNode VisitUsingStatement(BoundUsingStatement node) { if (node.ExpressionOpt != null) { VisitRvalue(node.ExpressionOpt); } if (node.DeclarationsOpt != null) { VisitStatement(node.DeclarationsOpt); } VisitStatement(node.Body); if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return null; } public abstract bool AwaitUsingAndForeachAddsPendingBranch { get; } public override BoundNode VisitFixedStatement(BoundFixedStatement node) { VisitStatement(node.Declarations); VisitStatement(node.Body); return null; } public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { BoundExpression expr = node.ExpressionOpt; VisitRvalue(expr); SetUnreachable(); return null; } public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, null)); SetUnreachable(); return null; } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { VisitRvalue(node.Expression); PendingBranches.Add(new PendingBranch(node, this.State, null)); return null; } public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) { return null; } public override BoundNode VisitDefaultExpression(BoundDefaultExpression node) { return null; } public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { VisitTypeExpression(node.SourceType); return null; } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { var savedState = this.State; SetState(UnreachableState()); Visit(node.Argument); SetState(savedState); return null; } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { VisitAddressOfOperand(node.Operand, shouldReadOperand: false); return null; } protected void VisitAddressOfOperand(BoundExpression operand, bool shouldReadOperand) { if (shouldReadOperand) { this.VisitRvalue(operand); } else { this.VisitLvalue(operand); } this.WriteArgument(operand, RefKind.Out, null); //Out because we know it will definitely be assigned. } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { VisitRvalue(node.Expression); VisitRvalue(node.Index); return null; } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { return null; } private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node) { VisitRvalue(node.Count); if (node.InitializerOpt != null && !node.InitializerOpt.Initializers.IsDefault) { foreach (var element in node.InitializerOpt.Initializers) { VisitRvalue(element); } } return null; } public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { return VisitStackAllocArrayCreationBase(node); } public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { return VisitStackAllocArrayCreationBase(node); } public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { // visit arguments as r-values VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.Constructor); return null; } public override BoundNode VisitArrayLength(BoundArrayLength node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { VisitCondition(node.Condition); Debug.Assert(this.IsConditionalState); if (node.JumpIfTrue) { PendingBranches.Add(new PendingBranch(node, this.StateWhenTrue, node.Label)); this.SetState(this.StateWhenFalse); } else { PendingBranches.Add(new PendingBranch(node, this.StateWhenFalse, node.Label)); this.SetState(this.StateWhenTrue); } return null; } public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } private BoundNode VisitObjectOrCollectionInitializerExpression(ImmutableArray<BoundExpression> initializers) { foreach (var initializer in initializers) { VisitRvalue(initializer); } return null; } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { var arguments = node.Arguments; if (!arguments.IsDefaultOrEmpty) { MethodSymbol method = null; if (node.MemberSymbol?.Kind == SymbolKind.Property) { var property = (PropertySymbol)node.MemberSymbol; method = GetReadMethod(property); } VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); } return null; } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { return null; } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (node.AddMethod.CallsAreOmitted(node.SyntaxTree)) { // If the underlying add method is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // flow analysis. TLocalState savedState = savedState = this.State.Clone(); SetUnreachable(); VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); this.State = savedState; } else { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); } return null; } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), method: null); return null; } public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node) { return null; } public override BoundNode VisitFieldEqualsValue(BoundFieldEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitPropertyEqualsValue(BoundPropertyEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitParameterEqualsValue(BoundParameterEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { return null; } public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { return null; } public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { return null; } public sealed override BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node) { throw ExceptionUtilities.Unreachable; } public sealed override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDiscardExpression(BoundDiscardExpression node) { return null; } private static MethodSymbol GetReadMethod(PropertySymbol property) => property.GetOwnOrInheritedGetMethod() ?? property.SetMethod; private static MethodSymbol GetWriteMethod(PropertySymbol property) => property.GetOwnOrInheritedSetMethod() ?? property.GetMethod; public override BoundNode VisitConstructorMethodBody(BoundConstructorMethodBody node) { Visit(node.Initializer); VisitMethodBodies(node.BlockBody, node.ExpressionBody); return null; } public override BoundNode VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node) { VisitMethodBodies(node.BlockBody, node.ExpressionBody); return null; } public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { TLocalState leftState; if (RegularPropertyAccess(node.LeftOperand) && (BoundPropertyAccess)node.LeftOperand is var left && left.PropertySymbol is var property && property.RefKind == RefKind.None) { var readMethod = property.GetOwnOrInheritedGetMethod(); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); var savedState = this.State.Clone(); AdjustStateForNullCoalescingAssignmentNonNullCase(node); leftState = this.State.Clone(); SetState(savedState); VisitAssignmentOfNullCoalescingAssignment(node, left); } else { VisitRvalue(node.LeftOperand, isKnownToBeAnLvalue: true); var savedState = this.State.Clone(); AdjustStateForNullCoalescingAssignmentNonNullCase(node); leftState = this.State.Clone(); SetState(savedState); VisitAssignmentOfNullCoalescingAssignment(node, propertyAccessOpt: null); } Join(ref this.State, ref leftState); return null; } public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { Visit(node.InvokedExpression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature); return null; } public override BoundNode VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) { // This is not encountered in correct programs, but can be seen if the function pointer was // unable to be converted and the semantic model is used to query for information. Visit(node.Operand); return null; } /// <summary> /// This visitor represents just the assignment part of the null coalescing assignment /// operator. /// </summary> protected virtual void VisitAssignmentOfNullCoalescingAssignment( BoundNullCoalescingAssignmentOperator node, BoundPropertyAccess propertyAccessOpt) { VisitRvalue(node.RightOperand); if (propertyAccessOpt != null) { var symbol = propertyAccessOpt.PropertySymbol; var writeMethod = symbol.GetOwnOrInheritedSetMethod(); PropertySetter(node, propertyAccessOpt.ReceiverOpt, writeMethod); } } public override BoundNode VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node) { return null; } public override BoundNode VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) { return null; } public override BoundNode VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node) { return null; } /// <summary> /// This visitor represents just the non-assignment part of the null coalescing assignment /// operator (when the left operand is non-null). /// </summary> protected virtual void AdjustStateForNullCoalescingAssignmentNonNullCase(BoundNullCoalescingAssignmentOperator node) { } private void VisitMethodBodies(BoundBlock blockBody, BoundBlock expressionBody) { if (blockBody == null) { Visit(expressionBody); return; } else if (expressionBody == null) { Visit(blockBody); return; } // In error cases we have two bodies. These are two unrelated pieces of code, // they are not executed one after another. As we don't really know which one the developer // intended to use, we need to visit both. We are going to pretend that there is // an unconditional fork in execution and then we are converging after each body is executed. // For example, if only one body assigns an out parameter, then after visiting both bodies // we should consider that parameter is not definitely assigned. // Note, that today this code is not executed for regular definite assignment analysis. It is // only executed for region analysis. TLocalState initialState = this.State.Clone(); Visit(blockBody); TLocalState afterBlock = this.State; SetState(initialState); Visit(expressionBody); Join(ref this.State, ref afterBlock); } #endregion visitors } /// <summary> /// The possible places that we are processing when there is a region. /// </summary> /// <remarks> /// This should be nested inside <see cref="AbstractFlowPass{TLocalState, TLocalFunctionState}"/> but is not due to https://github.com/dotnet/roslyn/issues/36992 . /// </remarks> internal enum RegionPlace { Before, Inside, After }; }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Nullability flow analysis. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed partial class NullableWalker : LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState> { /// <summary> /// Used to copy variable slots and types from the NullableWalker for the containing method /// or lambda to the NullableWalker created for a nested lambda or local function. /// </summary> internal sealed class VariableState { // Consider referencing the Variables instance directly from the original NullableWalker // rather than cloning. (Items are added to the collections but never replaced so the // collections are lazily populated but otherwise immutable. We'd probably want a // clone when analyzing from speculative semantic model though.) internal readonly VariablesSnapshot Variables; // The nullable state of all variables captured at the point where the function or lambda appeared. internal readonly LocalStateSnapshot VariableNullableStates; internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) { Variables = variables; VariableNullableStates = variableNullableStates; } } /// <summary> /// Data recorded for a particular analysis run. /// </summary> internal readonly struct Data { /// <summary> /// Number of entries tracked during analysis. /// </summary> internal readonly int TrackedEntries; /// <summary> /// True if analysis was required; false if analysis was optional and results dropped. /// </summary> internal readonly bool RequiredAnalysis; internal Data(int trackedEntries, bool requiredAnalysis) { TrackedEntries = trackedEntries; RequiredAnalysis = requiredAnalysis; } } /// <summary> /// Represents the result of visiting an expression. /// Contains a result type which tells us whether the expression may be null, /// and an l-value type which tells us whether we can assign null to the expression. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct VisitResult { public readonly TypeWithState RValueType; public readonly TypeWithAnnotations LValueType; public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) { RValueType = rValueType; LValueType = lValueType; // https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true //Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) || // RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions)); } public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) { RValueType = TypeWithState.Create(type, state); LValueType = TypeWithAnnotations.Create(type, annotation); Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything)); } internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}"; } /// <summary> /// Represents the result of visiting an argument expression. /// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/> /// for reanalyzing a lambda. /// </summary> [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] private readonly struct VisitArgumentResult { public readonly VisitResult VisitResult; public readonly Optional<LocalState> StateForLambda; public TypeWithState RValueType => VisitResult.RValueType; public TypeWithAnnotations LValueType => VisitResult.LValueType; public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda) { VisitResult = visitResult; StateForLambda = stateForLambda; } } private Variables _variables; /// <summary> /// Binder for symbol being analyzed. /// </summary> private readonly Binder _binder; /// <summary> /// Conversions with nullability and unknown matching any. /// </summary> private readonly Conversions _conversions; /// <summary> /// 'true' if non-nullable member warnings should be issued at return points. /// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type. /// </summary> private readonly bool _useConstructorExitWarnings; /// <summary> /// If true, the parameter types and nullability from _delegateInvokeMethod is used for /// initial parameter state. If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeParameterTypes; /// <summary> /// If true, the return type and nullability from _delegateInvokeMethod is used. /// If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeReturnType; /// <summary> /// Method signature used for return or parameter types. Distinct from CurrentSymbol signature /// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer. /// </summary> private MethodSymbol? _delegateInvokeMethod; /// <summary> /// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer. /// </summary> private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; /// <summary> /// Invalid type, used only to catch Visit methods that do not set /// _result.Type. See VisitExpressionWithoutStackGuard. /// </summary> private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull); /// <summary> /// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the /// compiler. /// </summary> private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt; /// <summary> /// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of /// this walker. /// </summary> private readonly SnapshotManager.Builder? _snapshotBuilderOpt; // https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported private bool _disableNullabilityAnalysis; /// <summary> /// State of method group receivers, used later when analyzing the conversion to a delegate. /// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.) /// </summary> private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt; /// <summary> /// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls. /// </summary> private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt; /// <summary> /// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This /// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These /// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value. /// </summary> private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion => _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.GetInstance(); /// <summary> /// True if we're analyzing speculative code. This turns off some initialization steps /// that would otherwise be taken. /// </summary> private readonly bool _isSpeculative; /// <summary> /// True if this walker was created using an initial state. /// </summary> private readonly bool _hasInitialState; #if DEBUG /// <summary> /// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>. /// </summary> private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization, BoundKind.ObjectInitializerExpression, BoundKind.CollectionInitializerExpression, BoundKind.DynamicCollectionElementInitializer); #endif /// <summary> /// The result and l-value type of the last visited expression. /// </summary> private VisitResult _visitResult; /// <summary> /// The visit result of the receiver for the current conditional access. /// /// For example: A conditional invocation uses a placeholder as a receiver. By storing the /// visit result from the actual receiver ahead of time, we can give this placeholder a correct result. /// </summary> private VisitResult _currentConditionalReceiverVisitResult; /// <summary> /// The result type represents the state of the last visited expression. /// </summary> private TypeWithState ResultType { get => _visitResult.RValueType; } private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) { SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability); } /// <summary> /// Force the inference of the LValueResultType from ResultType. /// </summary> private void UseRvalueOnly(BoundExpression? expression) { SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false); } private TypeWithAnnotations LvalueResultType { get => _visitResult.LValueType; } private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) { SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type); } /// <summary> /// Force the inference of the ResultType from LValueResultType. /// </summary> private void UseLvalueOnly(BoundExpression? expression) { SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true); } private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) { _visitResult = new VisitResult(resultType, lvalueType); if (updateAnalyzedNullability) { SetAnalyzedNullability(expression, _visitResult, isLvalue); } } private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable(); /// <summary> /// Sets the analyzed nullability of the expression to be the given result. /// </summary> private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) { if (expr == null || _disableNullabilityAnalysis) return; #if DEBUG // https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't // changing the observable results of GetTypeInfo beyond nullability information. //Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type), // $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}"); #endif if (_analyzedNullabilityMapOpt != null) { // https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions #if false if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing)) { if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable))) { switch (isLvalue) { case true: Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(), $"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}"); break; case false: Debug.Assert(existing.Info.FlowState == result.RValueType.State, $"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}"); break; case null: Debug.Assert(existing.Info.Equals((NullabilityInfo)result), $"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})"); break; } } } #endif _analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()), // https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely // with the existing type expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type); } } /// <summary> /// Placeholder locals, e.g. for objects being constructed. /// </summary> private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt; /// <summary> /// For methods with annotations, we'll need to visit the arguments twice. /// Once for diagnostics and once for result state (but disabling diagnostics). /// </summary> private bool _disableDiagnostics = false; /// <summary> /// Whether we are going to read the currently visited expression. /// </summary> private bool _expressionIsRead = true; /// <summary> /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when /// it's encountered. /// </summary> private int _lastConditionalAccessSlot = -1; private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; protected override void Free() { _nestedFunctionVariables?.Free(); _awaitablePlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 }); _conditionalInfoForConversionOpt?.Free(); base.Free(); } private NullableWalker( CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object); _variables = variables ?? Variables.Create(symbol); _binder = binder; _conversions = (Conversions)conversions.WithNullability(true); _useConstructorExitWarnings = useConstructorExitWarnings; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; _delegateInvokeMethod = delegateInvokeMethodOpt; _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; _returnTypesOpt = returnTypesOpt; _snapshotBuilderOpt = snapshotBuilderOpt; _isSpeculative = isSpeculative; _hasInitialState = variables is { }; } public string GetDebuggerDisplay() { if (this.IsConditionalState) { return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}"; } else { return $"{{{GetType().Name} {Dump(State)}{"}"}"; } } // For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; protected override void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth && compilation.NullableAnalysisData is { MaxRecursionDepth: var depth } && depth > 0 && recursionDepth > depth) { throw new InsufficientExecutionStackException(); } base.EnsureSufficientExecutionStack(recursionDepth); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) { return _variables.TryGetValue(identifier, out slot); } protected override int AddVariable(VariableIdentifier identifier) { return _variables.Add(identifier); } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { if (_returnTypesOpt != null) { _returnTypesOpt.Clear(); } this.Diagnostics.Clear(); this.regionPlace = RegionPlace.Before; if (!_isSpeculative) { ParameterSymbol methodThisParameter = MethodThisParameter; EnterParameters(); // assign parameters if (methodThisParameter is object) { EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); } makeNotNullMembersMaybeNull(); // We need to create a snapshot even of the first node, because we want to have the state of the initial parameters. _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); } ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion); if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings) { EnforceDoesNotReturn(syntaxOpt: null); enforceMemberNotNull(syntaxOpt: null, this.State); enforceNotNull(null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { enforceNotNull(returnStatement.Syntax, pendingReturn.State); enforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } } return pendingReturns; void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } var method = _symbol as MethodSymbol; if (method is object) { if (method.IsConstructor()) { Debug.Assert(_useConstructorExitWarnings); var thisSlot = 0; if (method.RequiresInstanceReceiver) { method.TryGetThisParameter(out var thisParameter); Debug.Assert(thisParameter is object); thisSlot = GetOrCreateSlot(thisParameter); } // https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault(); foreach (var member in method.ContainingType.GetMembersUnordered()) { checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation); } } else { do { foreach (var memberName in method.NotNullMembers) { enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName); } method = method.OverriddenMethod; } while (method != null); } } } void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation) { var isStatic = !constructor.RequiresInstanceReceiver(); if (member.IsStatic != isStatic) { return; } // This is not required for correctness, but in the case where the member has // an initializer, we know we've assigned to the member and // have given any applicable warnings about a bad value going in. // Therefore we skip this check when the member has an initializer to reduce noise. if (HasInitializer(member)) { return; } TypeWithAnnotations fieldType; FieldSymbol? field; Symbol symbol; switch (member) { case FieldSymbol f: fieldType = f.TypeWithAnnotations; field = f; symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f; break; case EventSymbol e: fieldType = e.TypeWithAnnotations; field = e.AssociatedField; symbol = e; if (field is null) { return; } break; default: return; } if (field.IsConst) { return; } if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType()) { return; } var annotations = symbol.GetFlowAnalysisAnnotations(); if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { // We assume that if a member has AllowNull then the user // does not care that we exit at a point where the member might be null. return; } fieldType = ApplyUnconditionalAnnotations(fieldType, annotations); if (!fieldType.NullableAnnotation.IsNotAnnotated()) { return; } var slot = GetOrCreateSlot(symbol, thisSlot); if (slot < 0) { return; } var memberState = state[slot]; var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0 ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'? { Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name); } } void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) { foreach (var member in method.ContainingType.GetMembers(memberName)) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name); } } } void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } if (_symbol is MethodSymbol method) { foreach (var memberName in method.NotNullWhenTrueMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); } foreach (var memberName in method.NotNullWhenFalseMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); } } void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState) { foreach (var member in members) { // For non-constant values, only complain if we were able to analyze a difference for this member between two branches if (memberHasBadState(member, state) != memberHasBadState(member, otherState)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) { if (_symbol is MethodSymbol method) { var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers; foreach (var memberName in notNullMembers) { foreach (var member in method.ContainingType.GetMembers(memberName)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } } void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false"); } } bool memberHasBadState(Symbol member, LocalState state) { switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { var parameterState = state[memberSlot]; return !parameterState.IsNotNull(); } else { return false; } case SymbolKind.Event: case SymbolKind.Method: break; } return false; } void makeNotNullMembersMaybeNull() { if (_symbol is MethodSymbol method) { if (method.IsConstructor()) { if (needsDefaultInitialStateForMembers()) { foreach (var member in method.ContainingType.GetMembersUnordered()) { if (member.IsStatic != method.IsStatic) { continue; } var memberToInitialize = member; switch (member) { case PropertySymbol: // skip any manually implemented properties. continue; case FieldSymbol { IsConst: true }: continue; case FieldSymbol { AssociatedSymbol: PropertySymbol prop }: // this is a property where assigning 'default' causes us to simply update // the state to the output state of the property // thus we skip setting an initial state for it here if (IsPropertyOutputMoreStrictThanInput(prop)) { continue; } // We want to initialize auto-property state to the default state, but not computed properties. memberToInitialize = prop; break; default: break; } var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize); if (memberSlot > 0) { var type = memberToInitialize.GetTypeOrReturnType(); if (!type.NullableAnnotation.IsOblivious()) { this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } } } else { do { makeMembersMaybeNull(method, method.NotNullMembers); makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); method = method.OverriddenMethod; } while (method != null); } } bool needsDefaultInitialStateForMembers() { if (_hasInitialState) { return false; } // We don't use a default initial state for value type instance constructors without `: this()` because // any usages of uninitialized fields will get definite assignment errors anyway. if (!method.HasThisConstructorInitializer(out _) && (!method.ContainingType.IsValueType || method.IsStatic)) { return true; } return method.IncludeFieldInitializersInBody(); } } void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members) { foreach (var memberName in members) { makeMemberMaybeNull(method, memberName); } } void makeMemberMaybeNull(MethodSymbol method, string memberName) { var type = method.ContainingType; foreach (var member in type.GetMembers(memberName)) { if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { this.State[memberSlot] = NullableFlowState.MaybeNull; } } } void enforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { var parameters = this.MethodParameters; if (!parameters.IsEmpty) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } foreach (var parameter in parameters) { // For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot]) { reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue); reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { // example: return (bool)true; enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } void reportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) { if (parameterHasBadConditionalState(parameter, sense, stateWhen)) { // Parameter '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); } } void enforceNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } foreach (var parameter in this.MethodParameters) { var slot = GetOrCreateSlot(parameter); if (slot <= 0) { continue; } var annotations = parameter.FlowAnalysisAnnotations; var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; var parameterState = state[slot]; if (hasNotNull && parameterState.MayBeNull()) { // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen) { var refKind = parameter.RefKind; if (refKind != RefKind.Out && refKind != RefKind.Ref) { return false; } var slot = GetOrCreateSlot(parameter); if (slot > 0) { var parameterState = stateWhen[slot]; // On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning. // We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen. FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations; if (sense) { bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; return (hasNotNullWhenTrue && parameterState.MayBeNull()) || (hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } else { bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; return (hasNotNullWhenFalse && parameterState.MayBeNull()) || (hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } } return false; } int getSlotForFieldOrPropertyOrEvent(Symbol member) { if (member.Kind != SymbolKind.Field && member.Kind != SymbolKind.Property && member.Kind != SymbolKind.Event) { return -1; } int containingSlot = 0; if (!member.IsStatic) { if (MethodThisParameter is null) { return -1; } containingSlot = GetOrCreateSlot(MethodThisParameter); if (containingSlot < 0) { return -1; } Debug.Assert(containingSlot > 0); } return GetOrCreateSlot(member, containingSlot); } } private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) { if (inputParamNames.IsEmpty || outputState.IsNotNull()) { return; } foreach (var inputParam in parameters) { if (inputParamNames.Contains(inputParam.Name) && GetOrCreateSlot(inputParam) is > 0 and int inputSlot && state[inputSlot].IsNotNull()) { var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); if (outputParam is object) { // Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name); } else if (CurrentSymbol is MethodSymbol { IsAsync: false }) { // Return value must be non-null because parameter '{0}' is non-null. Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name); } break; } } } private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) { // DoesNotReturn is only supported in member methods if (CurrentSymbol is MethodSymbol { ContainingSymbol: TypeSymbol _ } method && ((method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) && this.IsReachable()) { // A method marked [DoesNotReturn] should not return. ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation()); } } /// <summary> /// Analyzes a method body if settings indicate we should. /// </summary> internal static void AnalyzeIfNeeded( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState) { if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) { if (compilation.IsNullableAnalysisEnabledAlways) { // Once we address https://github.com/dotnet/roslyn/issues/46579 we should also always pass `getFinalNullableState: true` in debug mode. // We will likely always need to write a 'null' out for the out parameter in this code path, though, because // we don't want to introduce behavior differences between debug and release builds Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: false, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) { finalNullableState = null; return; } Debug.Assert(node.SyntaxTree is object); var binder = method is SynthesizedSimpleProgramEntryPointSymbol entryPoint ? entryPoint.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax); var conversions = binder.Conversions; Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: initialNullableState, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. Only used for semantic model and debug verification. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { var unusedDiagnostics = DiagnosticBag.GetInstance(); Binder.ProcessedFieldInitializers initializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref initializers); NullableWalker.AnalyzeIfNeeded( compilation, method, InitializerRewriter.RewriteConstructor(initializers.BoundInitializers, method), unusedDiagnostics, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out var afterInitializersState); unusedDiagnostics.Free(); return afterInitializersState; } return null; } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information. This method is only /// used when nullable is explicitly enabled for all methods but disabled otherwise to verify that /// correct semantic information is being recorded for all bound nodes. The results are thrown away. /// </summary> internal static void AnalyzeWithoutRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) { _ = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState: GetAfterInitializersState(compilation, symbol), diagnostics, createSnapshots, requiresAnalysis: false); } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information, and returns an /// updated BoundNode with the information populated. /// </summary> internal static BoundNode AnalyzeAndRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> analyzedNullabilitiesMap; (snapshotManager, analyzedNullabilitiesMap) = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); return Rewrite(analyzedNullabilitiesMap, snapshotManager, node, ref remappedSymbols); } private static (SnapshotManager?, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>) AnalyzeWithSemanticInfo( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); // Attributes don't have a symbol, which is what SnapshotBuilder uses as an index for maintaining global state. // Until we have a workaround for this, disable snapshots for null symbols. // https://github.com/dotnet/roslyn/issues/36066 var snapshotBuilder = createSnapshots && symbol != null ? new SnapshotManager.Builder() : null; Analyze( compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState, analyzedNullabilities, snapshotBuilder, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); var snapshotManager = snapshotBuilder?.ToManagerAndFree(); #if DEBUG // https://github.com/dotnet/roslyn/issues/34993 Enable for all calls if (isNullableAnalysisEnabledAnywhere(compilation)) { DebugVerifier.Verify(analyzedNullabilitiesMap, snapshotManager, node); } static bool isNullableAnalysisEnabledAnywhere(CSharpCompilation compilation) { if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { return true; } return compilation.SyntaxTrees.Any(tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new Text.TextSpan(0, tree.Length)) == true); } #endif return (snapshotManager, analyzedNullabilitiesMap); } internal static BoundNode AnalyzeAndRewriteSpeculation( int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); var newSnapshotBuilder = new SnapshotManager.Builder(); var (variables, localState) = originalSnapshots.GetSnapshot(position); var symbol = variables.Symbol; var walker = new NullableWalker( binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, binder.Conversions, Variables.Create(variables), returnTypesOpt: null, analyzedNullabilities, newSnapshotBuilder, isSpeculative: true); try { Analyze(walker, symbol, diagnostics: null, LocalState.Create(localState), snapshotBuilderOpt: newSnapshotBuilder); } finally { walker.Free(); } var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); newSnapshots = newSnapshotBuilder.ToManagerAndFree(); #if DEBUG DebugVerifier.Verify(analyzedNullabilitiesMap, newSnapshots, node); #endif return Rewrite(analyzedNullabilitiesMap, newSnapshots, node, ref remappedSymbols); } private static BoundNode Rewrite(ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var remappedSymbolsBuilder = ImmutableDictionary.CreateBuilder<Symbol, Symbol>(Symbols.SymbolEqualityComparer.ConsiderEverything, Symbols.SymbolEqualityComparer.ConsiderEverything); if (remappedSymbols is object) { // When we're rewriting for the speculative model, there will be a set of originally-mapped symbols, and we need to // use them in addition to any symbols found during this pass of the walker. remappedSymbolsBuilder.AddRange(remappedSymbols); } var rewriter = new NullabilityRewriter(updatedNullabilities, snapshotManager, remappedSymbolsBuilder); var rewrittenNode = rewriter.Visit(node); remappedSymbols = remappedSymbolsBuilder.ToImmutable(); return rewrittenNode; } private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) { return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); } /// <summary> /// Returns true if the nullable analysis is needed for the region represented by <paramref name="syntaxNode"/>. /// The syntax node is used to determine the overall nullable context for the region. /// </summary> internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) { return HasRequiredLanguageVersion(compilation) && (compilation.IsNullableAnalysisEnabledIn(syntaxNode) || compilation.IsNullableAnalysisEnabledAlways); } /// <summary>Analyzes a node in a "one-off" context, such as for attributes or parameter default values.</summary> /// <remarks><paramref name="syntax"/> is the syntax span used to determine the overall nullable context.</remarks> internal static void AnalyzeIfNeeded( Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) { bool requiresAnalysis = true; var compilation = binder.Compilation; if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(syntax)) { if (!compilation.IsNullableAnalysisEnabledAlways) { return; } diagnostics = new DiagnosticBag(); requiresAnalysis = false; } Analyze( compilation, symbol: null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); } internal static void Analyze( CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) { var symbol = lambda.Symbol; var variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); var walker = new NullableWalker( compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: useDelegateInvokeParameterTypes, useDelegateInvokeReturnType: useDelegateInvokeReturnType, delegateInvokeMethodOpt: delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, returnTypesOpt, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); try { var localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); Analyze(walker, symbol, diagnostics, localState, snapshotBuilderOpt: null); } finally { walker.Free(); } } private static void Analyze( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { Debug.Assert(diagnostics != null); var walker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, initialState is null ? null : Variables.Create(initialState.Variables), returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); finalNullableState = null; try { Analyze(walker, symbol, diagnostics, initialState is null ? (Optional<LocalState>)default : LocalState.Create(initialState.VariableNullableStates), snapshotBuilderOpt, requiresAnalysis); if (getFinalNullableState) { Debug.Assert(!walker.IsConditionalState); finalNullableState = GetVariableState(walker._variables, walker.State); } } finally { walker.Free(); } } private static void Analyze( NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional<LocalState> initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) { Debug.Assert(snapshotBuilderOpt is null || symbol is object); var previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol!) ?? -1; try { bool badRegion = false; ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion, initialState); diagnostics?.AddRange(walker.Diagnostics); Debug.Assert(!badRegion); } catch (CancelledByStackGuardException ex) when (diagnostics != null) { ex.AddAnError(diagnostics); } finally { snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); } walker.RecordNullableAnalysisData(symbol, requiresAnalysis); } private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) { if (compilation.NullableAnalysisData?.Data is { } state) { var key = (object?)symbol ?? methodMainNode.Syntax; if (state.TryGetValue(key, out var result)) { Debug.Assert(result.RequiredAnalysis == requiredAnalysis); } else { state.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); } } } private SharedWalkerState SaveSharedState() { return new SharedWalkerState(_variables.CreateSnapshot()); } private void TakeIncrementalSnapshot(BoundNode? node) { Debug.Assert(!IsConditionalState); _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); } private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) { if (_snapshotBuilderOpt is null) { return; } var lambdaIsExactMatch = false; if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) { if (!AreLambdaAndNewDelegateSimilar(l, n)) { return; } lambdaIsExactMatch = updatedSymbol.Equals(boundLambda.Type!.GetDelegateType(), TypeCompareKind.ConsiderEverything); } #if DEBUG Debug.Assert(node is object); Debug.Assert(AreCloseEnough(originalSymbol, updatedSymbol), $"Attempting to set {node.Syntax} from {originalSymbol.ToDisplayString()} to {updatedSymbol.ToDisplayString()}"); #endif if (lambdaIsExactMatch || Symbol.Equals(originalSymbol, updatedSymbol, TypeCompareKind.ConsiderEverything)) { // If the symbol is reset, remove the updated symbol so we don't needlessly update the // bound node later on. We do this unconditionally, as Remove will just return false // if the key wasn't in the dictionary. _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); } else { _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); } } protected override void Normalize(ref LocalState state) { if (!state.Reachable) return; state.Normalize(this, _variables); } private NullableFlowState GetDefaultState(ref LocalState state, int slot) { Debug.Assert(slot > 0); if (!state.Reachable) return NullableFlowState.NotNull; var variable = _variables[slot]; var symbol = variable.Symbol; switch (symbol.Kind) { case SymbolKind.Local: { var local = (LocalSymbol)symbol; if (!_variables.TryGetType(local, out TypeWithAnnotations localType)) { localType = local.TypeWithAnnotations; } return localType.ToTypeWithState().State; } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (!_variables.TryGetType(parameter, out TypeWithAnnotations parameterType)) { parameterType = parameter.TypeWithAnnotations; } return GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; } case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return GetDefaultState(symbol); case SymbolKind.ErrorType: return NullableFlowState.NotNull; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) { receiver = null; member = null; switch (expr.Kind) { case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; member = fieldSymbol; if (fieldSymbol.IsFixedSizeBuffer) { return false; } if (fieldSymbol.IsStatic) { return true; } receiver = fieldAccess.ReceiverOpt; break; } case BoundKind.EventAccess: { var eventAccess = (BoundEventAccess)expr; var eventSymbol = eventAccess.EventSymbol; // https://github.com/dotnet/roslyn/issues/29901 Use AssociatedField for field-like events? member = eventSymbol; if (eventSymbol.IsStatic) { return true; } receiver = eventAccess.ReceiverOpt; break; } case BoundKind.PropertyAccess: { var propAccess = (BoundPropertyAccess)expr; var propSymbol = propAccess.PropertySymbol; member = propSymbol; if (propSymbol.IsStatic) { return true; } receiver = propAccess.ReceiverOpt; break; } } Debug.Assert(member?.RequiresInstanceReceiver() ?? true); return member is object && receiver is object && receiver.Kind != BoundKind.TypeExpression && receiver.Type is object; } protected override int MakeSlot(BoundExpression node) { int result = makeSlot(node); #if DEBUG if (result != -1) { // Check that the slot represents a value of an equivalent type to the node TypeSymbol slotType = NominalSlotType(result); TypeSymbol? nodeType = node.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = this.compilation.Conversions; Debug.Assert(node.HasErrors || nodeType!.IsErrorType() || conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(slotType, nodeType, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(slotType, nodeType, ref discardedUseSiteInfo)); } #endif return result; int makeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: { var method = getTopLevelMethod(_symbol as MethodSymbol); var thisParameter = method?.ThisParameter; return thisParameter is object ? GetOrCreateSlot(thisParameter) : -1; } case BoundKind.Conversion: { int slot = getPlaceholderSlot(node); if (slot > 0) { return slot; } var conv = (BoundConversion)node; switch (conv.Conversion.Kind) { case ConversionKind.ExplicitNullable: { var operand = conv.Operand; var operandType = operand.Type; var convertedType = conv.Type; if (AreNullableAndUnderlyingTypes(operandType, convertedType, out _)) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. // For instance, in the following, when evaluating `((A)a).B` we need to recognize // the nullability of `(A)a` (not nullable) and the slot (the slot for `a.Value`). // struct A { B? B; } // struct B { } // if (a?.B != null) _ = ((A)a).B.Value; // no warning int containingSlot = MakeSlot(operand); return containingSlot < 0 ? -1 : GetNullableOfTValueSlot(operandType, containingSlot, out _); } } break; case ConversionKind.Identity: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.Boxing: // No need to create a slot for the boxed value (in the Boxing case) since assignment already // clones slots and there is not another scenario where creating a slot is observable. return MakeSlot(conv.Operand); } } break; case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.ObjectCreationExpression: case BoundKind.DynamicObjectCreationExpression: case BoundKind.AnonymousObjectCreationExpression: case BoundKind.NewT: case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return getPlaceholderSlot(node); case BoundKind.ConditionalAccess: return getPlaceholderSlot(node); case BoundKind.ConditionalReceiver: return _lastConditionalAccessSlot; default: { int slot = getPlaceholderSlot(node); return (slot > 0) ? slot : base.MakeSlot(node); } } return -1; } int getPlaceholderSlot(BoundExpression expr) { if (_placeholderLocalsOpt != null && _placeholderLocalsOpt.TryGetValue(expr, out var placeholder)) { return GetOrCreateSlot(placeholder); } return -1; } static MethodSymbol? getTopLevelMethod(MethodSymbol? method) { while (method is object) { var container = method.ContainingSymbol; if (container.Kind == SymbolKind.NamedType) { return method; } method = container as MethodSymbol; } return null; } } protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) return -1; return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); } private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode { if (nodes.IsDefault) { return; } foreach (var node in nodes) { Visit(node); Unsplit(); } } private void VisitWithoutDiagnostics(BoundNode? node) { var previousDiagnostics = _disableDiagnostics; _disableDiagnostics = true; Visit(node); _disableDiagnostics = previousDiagnostics; } protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) { Visit(node); VisitRvalueEpilogue(node); } /// <summary> /// The contents of this method, particularly <see cref="UseRvalueOnly"/>, are problematic when /// inlined. The methods themselves are small but they end up allocating significantly larger /// frames due to the use of biggish value types within them. The <see cref="VisitRvalue"/> method /// is used on a hot path for fluent calls and this size change is enough that it causes us /// to exceed our thresholds in EndToEndTests.OverflowOnFluentCall. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void VisitRvalueEpilogue(BoundExpression? node) { Unsplit(); UseRvalueOnly(node); // drop lvalue part } private TypeWithState VisitRvalueWithState(BoundExpression? node) { VisitRvalue(node); return ResultType; } private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) { VisitLValue(node); Unsplit(); return LvalueResultType; } private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) { return typeOpt ?? (object)"<null>"; } private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) { return parameterOpt is null ? (object)"" : new FormattedSymbol(parameterOpt, SymbolDisplayFormat.ShortFormat); } private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) { var containingSymbol = parameterOpt?.ContainingSymbol; return containingSymbol is null ? (object)"" : new FormattedSymbol(containingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat); } private enum AssignmentKind { Assignment, Return, Argument, ForEachIterationVariable } /// <summary> /// Should we warn for assigning this state into this type? /// /// This should often be checked together with <seealso cref="IsDisallowedNullAssignment(TypeWithState, FlowAnalysisAnnotations)"/> /// It catches putting a `null` into a `[DisallowNull]int?` for example, which cannot simply be represented as a non-nullable target type. /// </summary> private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) { if (!type.HasType || type.Type.IsValueType) { return false; } switch (type.NullableAnnotation) { case NullableAnnotation.Oblivious: case NullableAnnotation.Annotated: return false; } switch (state) { case NullableFlowState.NotNull: return false; case NullableFlowState.MaybeNull: if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && !(type.Type is TypeParameterSymbol { IsNotNullable: true })) { return false; } break; } return true; } /// <summary> /// Reports top-level nullability problem in assignment. /// Any conversion of the value should have been applied. /// </summary> private void ReportNullableAssignmentIfNecessary( BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) { // Callers should apply any conversions before calling this method // (see https://github.com/dotnet/roslyn/issues/39867). if (targetType.HasType && !targetType.Type.Equals(valueType.Type, TypeCompareKind.AllIgnoreOptions)) { return; } if (value == null || // This prevents us from giving undesired warnings for synthesized arguments for optional parameters, // but allows us to give warnings for synthesized assignments to record properties and for parameter default values at the declaration site. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument) || !ShouldReportNullableAssignment(targetType, valueType.State)) { return; } location ??= value.Syntax.GetLocation(); var unwrappedValue = SkipReferenceConversions(value); if (unwrappedValue.IsSuppressed) { return; } if (value.ConstantValue?.IsNull == true && !useLegacyWarnings) { // Report warning converting null literal to non-nullable reference type. // target (e.g.: `object F() => null;` or calling `void F(object y)` with `F(null)`). ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); } else if (assignmentKind == AssignmentKind.Argument) { ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); LearnFromNonNullTest(value, ref State); } else if (useLegacyWarnings) { if (isMaybeDefaultValue(valueType) && !allowUnconstrainedTypeParameterAnnotations(compilation)) { // No W warning reported assigning or casting [MaybeNull]T value to T // because there is no syntax for declaring the target type as [MaybeNull]T. return; } ReportNonSafetyDiagnostic(location); } else { ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); } static bool isMaybeDefaultValue(TypeWithState valueType) { return valueType.Type?.TypeKind == TypeKind.TypeParameter && valueType.State == NullableFlowState.MaybeDefault; } static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); return requiredVersion <= compilation.LanguageVersion; } } internal static bool AreParameterAnnotationsCompatible( RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) { // We've already checked types and annotations, let's check nullability attributes as well // Return value is treated as an `out` parameter (or `ref` if it is a `ref` return) if (refKind == RefKind.Ref) { // ref variables are invariant return AreParameterAnnotationsCompatible(RefKind.None, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true) && AreParameterAnnotationsCompatible(RefKind.Out, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); } if (refKind == RefKind.None || refKind == RefKind.In) { // pre-condition attributes // Check whether we can assign a value from overridden parameter to overriding var valueState = GetParameterState(overriddenType, overriddenAnnotations); if (isBadAssignment(valueState, overridingType, overridingAnnotations)) { return false; } // unconditional post-condition attributes on inputs bool overridingHasNotNull = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; bool overriddenHasNotNull = (overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; if (overriddenHasNotNull && !overridingHasNotNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise not to return if parameter is null) return false; } bool overridingHasMaybeNull = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; bool overriddenHasMaybeNull = (overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; if (overriddenHasMaybeNull && !overridingHasMaybeNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise to only return if parameter is null) return false; } } if (refKind == RefKind.Out) { // post-condition attributes (`Maybe/NotNull` and `Maybe/NotNullWhen`) if (!canAssignOutputValueWhen(true) || !canAssignOutputValueWhen(false)) { return false; } } return true; bool canAssignOutputValueWhen(bool sense) { var valueWhen = ApplyUnconditionalAnnotations( overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)); var destAnnotationsWhen = ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)); if (isBadAssignment(valueWhen, overriddenType, destAnnotationsWhen)) { // Can't assign value from overriding to overridden in 'sense' case return false; } return true; } static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) { if (ShouldReportNullableAssignment( ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) { return true; } if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) { return true; } return false; } // Convert both conditional annotations to unconditional ones or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) { if (sense) { var unconditionalAnnotationWhenTrue = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenTrue, FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); } var unconditionalAnnotationWhenFalse = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenFalse, FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); } // Convert Maybe/NotNullWhen into Maybe/NotNull or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) { if ((annotations & conditionalAnnotation) != 0) { return annotations | replacementAnnotation; } return annotations & ~replacementAnnotation; } } private static bool IsDefaultValue(BoundExpression expr) { switch (expr.Kind) { case BoundKind.Conversion: { var conversion = (BoundConversion)expr; var conversionKind = conversion.Conversion.Kind; return (conversionKind == ConversionKind.DefaultLiteral || conversionKind == ConversionKind.NullLiteral) && IsDefaultValue(conversion.Operand); } case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; default: return false; } } private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); } private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); } /// <summary> /// Update tracked value on assignment. /// </summary> private void TrackNullableStateForAssignment( BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) { Debug.Assert(!IsConditionalState); if (this.State.Reachable) { if (!targetType.HasType) { return; } if (targetSlot <= 0 || targetSlot == valueSlot) { return; } if (!this.State.HasValue(targetSlot)) Normalize(ref this.State); var newState = valueType.State; SetStateAndTrackForFinally(ref this.State, targetSlot, newState); InheritDefaultState(targetType.Type, targetSlot); // https://github.com/dotnet/roslyn/issues/33428: Can the areEquivalentTypes check be removed // if InheritNullableStateOfMember asserts the member is valid for target and value? if (areEquivalentTypes(targetType, valueType)) { if (targetType.Type.IsReferenceType || targetType.TypeKind == TypeKind.TypeParameter || targetType.IsNullableType()) { if (valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot: targetSlot); } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) { InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, isDefaultValue: !(valueOpt is null) && IsDefaultValue(valueOpt), skipSlot: targetSlot); } } } static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) => target.Type.Equals(assignedValue.Type, TypeCompareKind.AllIgnoreOptions); } private void ReportNonSafetyDiagnostic(Location location) { ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); } private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) { ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); } private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) { Debug.Assert(ErrorFacts.NullableWarnings.Contains(MessageProvider.Instance.GetIdForErrorCode((int)errorCode))); if (IsReachable() && !_disableDiagnostics) { Diagnostics.Add(errorCode, location, arguments); } } private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) { Debug.Assert(targetSlot > 0); Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType)); if (skipSlot < 0) { skipSlot = targetSlot; } if (!isDefaultValue && valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); } else { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType)) { InheritNullableStateOfMember(targetSlot, valueSlot, field, isDefaultValue: isDefaultValue, skipSlot); } } } private bool IsSlotMember(int slot, Symbol possibleMember) { TypeSymbol possibleBase = possibleMember.ContainingType; TypeSymbol possibleDerived = NominalSlotType(slot); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = _conversions.WithNullability(false); return conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } // 'skipSlot' is the original target slot that should be skipped in case of cycles. private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) { Debug.Assert(targetContainerSlot > 0); Debug.Assert(skipSlot > 0); // Ensure member is valid for target and value. if (!IsSlotMember(targetContainerSlot, member)) return; TypeWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType(); if (fieldOrPropertyType.Type.IsReferenceType || fieldOrPropertyType.TypeKind == TypeKind.TypeParameter || fieldOrPropertyType.IsNullableType()) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { NullableFlowState value = isDefaultValue ? NullableFlowState.MaybeNull : fieldOrPropertyType.ToTypeWithState().State; int valueMemberSlot = -1; if (valueContainerSlot > 0) { valueMemberSlot = VariableSlot(member, valueContainerSlot); if (valueMemberSlot == skipSlot) { return; } value = this.State.HasValue(valueMemberSlot) ? this.State[valueMemberSlot] : NullableFlowState.NotNull; } SetStateAndTrackForFinally(ref this.State, targetMemberSlot, value); if (valueMemberSlot > 0) { InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, skipSlot); } } } else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.Type)) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { int valueMemberSlot = (valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : -1; if (valueMemberSlot == skipSlot) { return; } InheritNullableStateOfTrackableStruct(fieldOrPropertyType.Type, targetMemberSlot, valueMemberSlot, isDefaultValue: isDefaultValue, skipSlot); } } } private TypeSymbol NominalSlotType(int slot) { return _variables[slot].Symbol.GetTypeOrReturnType().Type; } /// <summary> /// Whenever assigning a variable, and that variable is not declared at the point the state is being set, /// and the new state is not <see cref="NullableFlowState.NotNull"/>, this method should be called to perform the /// state setting and to ensure the mutation is visible outside the finally block when the mutation occurs in a /// finally block. /// </summary> private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) { state[slot] = newState; if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) { var tryState = NonMonotonicState.Value; if (tryState.HasVariable(slot)) { tryState[slot] = newState.Join(tryState[slot]); NonMonotonicState = tryState; } } } protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) { var tryState = other.GetStateForVariables(self.Id); Join(ref self, ref tryState); } private void InheritDefaultState(TypeSymbol targetType, int targetSlot) { Debug.Assert(targetSlot > 0); // Reset the state of any members of the target. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, targetSlot); foreach (var (variable, slot) in members) { var symbol = AsMemberOfType(targetType, variable.Symbol); SetStateAndTrackForFinally(ref this.State, slot, GetDefaultState(symbol)); InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot); } members.Free(); } private NullableFlowState GetDefaultState(Symbol symbol) => ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) { Debug.Assert(targetSlot > 0); Debug.Assert(valueSlot > 0); // Clone the state for members that have been set on the value. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, valueSlot); foreach (var (variable, slot) in members) { var member = variable.Symbol; Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); InheritNullableStateOfMember(targetSlot, valueSlot, member, isDefaultValue: false, skipSlot); } members.Free(); } protected override LocalState TopState() { var state = LocalState.ReachableState(_variables); state.PopulateAll(this); return state; } protected override LocalState UnreachableState() { return LocalState.UnreachableState(_variables); } protected override LocalState ReachableBottomState() { // Create a reachable state in which all variables are known to be non-null. return LocalState.ReachableState(_variables); } private void EnterParameters() { if (!(CurrentSymbol is MethodSymbol methodSymbol)) { return; } if (methodSymbol is SynthesizedRecordConstructor) { if (_hasInitialState) { // A record primary constructor's parameters are entered before analyzing initializers. // On the second pass, the correct parameter states (potentially modified by initializers) // are contained in the initial state. return; } } else if (methodSymbol.IsConstructor()) { if (!_hasInitialState) { // For most constructors, we only enter parameters after analyzing initializers. return; } } // The partial definition part may include optional parameters whose default values we want to simulate assigning at the beginning of the method methodSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol; var methodParameters = methodSymbol.Parameters; var signatureParameters = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod! : methodSymbol).Parameters; // save a state representing the possibility that parameter default values were not assigned to the parameters. var parameterDefaultsNotAssignedState = State.Clone(); for (int i = 0; i < methodParameters.Length; i++) { var parameter = methodParameters[i]; // In error scenarios, the method can potentially have more parameters than the signature. If so, use the parameter type for those // errored parameters var parameterType = i >= signatureParameters.Length ? parameter.TypeWithAnnotations : signatureParameters[i].TypeWithAnnotations; EnterParameter(parameter, parameterType); } Join(ref State, ref parameterDefaultsNotAssignedState); } private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) { _variables.SetType(parameter, parameterType); if (parameter.RefKind != RefKind.Out) { int slot = GetOrCreateSlot(parameter); Debug.Assert(!IsConditionalState); if (slot > 0) { var state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; this.State[slot] = state; if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) { InheritNullableStateOfTrackableStruct( parameterType.Type, slot, valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } } } } public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) { var parameter = equalsValue.Parameter; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); var resultType = VisitOptionalImplicitConversion( equalsValue.Value, parameterLValueType, useLegacyWarnings: false, trackMembers: false, assignmentKind: AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); return null; } internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); } if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); } return parameterType.ToTypeWithState(); } public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) { Debug.Assert(!IsConditionalState); var expr = node.ExpressionOpt; if (expr == null) { EnforceDoesNotReturn(node.Syntax); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return null; } // Should not convert to method return type when inferring return type (when _returnTypesOpt != null). if (_returnTypesOpt == null && TryGetReturnType(out TypeWithAnnotations returnType, out FlowAnalysisAnnotations returnAnnotations)) { if (node.RefKind == RefKind.None && returnType.Type.SpecialType == SpecialType.System_Boolean) { // visit the expression without unsplitting, then check parameters marked with flow analysis attributes Visit(expr); } else { TypeWithState returnState; if (node.RefKind == RefKind.None) { returnState = VisitOptionalImplicitConversion(expr, returnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); } else { // return ref expr; returnState = VisitRefExpression(expr, returnType); } // If the return has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(returnState, ToInwardAnnotations(returnAnnotations), node.Syntax.Location, boundValueOpt: expr); } } else { var result = VisitRvalueWithState(expr); if (_returnTypesOpt != null) { _returnTypesOpt.Add((node, result.ToTypeWithAnnotations(compilation))); } } EnforceDoesNotReturn(node.Syntax); if (IsConditionalState) { var joinedState = this.StateWhenTrue.Clone(); Join(ref joinedState, ref this.StateWhenFalse); PendingBranches.Add(new PendingBranch(node, joinedState, label: null, this.IsConditionalState, this.StateWhenTrue, this.StateWhenFalse)); } else { PendingBranches.Add(new PendingBranch(node, this.State, label: null)); } Unsplit(); if (CurrentSymbol is MethodSymbol method) { EnforceNotNullIfNotNull(node.Syntax, this.State, method.Parameters, method.ReturnNotNullIfParameterNotNull, ResultType.State, outputParam: null); } SetUnreachable(); return null; } private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) { Visit(expr); TypeWithState resultType = ResultType; if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) { var lvalueResultType = LvalueResultType; if (IsNullabilityMismatch(lvalueResultType, destinationType)) { // declared types must match ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); } } return resultType; } private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) { var method = CurrentSymbol as MethodSymbol; if (method is null) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } var delegateOrMethod = _useDelegateInvokeReturnType ? _delegateInvokeMethod! : method; var returnType = delegateOrMethod.ReturnTypeWithAnnotations; Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred); if (returnType.IsVoidType()) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } if (!method.IsAsync) { annotations = delegateOrMethod.ReturnTypeFlowAnalysisAnnotations; type = ApplyUnconditionalAnnotations(returnType, annotations); return true; } if (method.IsAsyncEffectivelyReturningGenericTask(compilation)) { type = ((NamedTypeSymbol)returnType.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); annotations = FlowAnalysisAnnotations.None; return true; } type = default; annotations = FlowAnalysisAnnotations.None; return false; } public override BoundNode? VisitLocal(BoundLocal node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); var type = GetDeclaredLocalResult(local); if (!node.Type.Equals(type.Type, TypeCompareKind.ConsiderEverything | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames)) { // When the local is used before or during initialization, there can potentially be a mismatch between node.LocalSymbol.Type and node.Type. We // need to prefer node.Type as we shouldn't be changing the type of the BoundLocal node during rewrite. // https://github.com/dotnet/roslyn/issues/34158 Debug.Assert(node.Type.IsErrorType() || type.Type.IsErrorType()); type = TypeWithAnnotations.Create(node.Type, type.NullableAnnotation); } SetResult(node, GetAdjustedResult(type.ToTypeWithState(), slot), type); SplitIfBooleanConstant(node); return null; } public override BoundNode? VisitBlock(BoundBlock node) { DeclareLocals(node.Locals); VisitStatementsWithLocalFunctions(node); return null; } private void VisitStatementsWithLocalFunctions(BoundBlock block) { // Since the nullable flow state affects type information, and types can be queried by // the semantic model, there needs to be a single flow state input to a local function // that cannot be path-dependent. To decide the local starting state we Meet the state // of captured variables from all the uses of the local function, computing the // conservative combination of all potential starting states. // // For performance we split the analysis into two phases: the first phase where we // analyze everything except the local functions, hoping to visit all of the uses of the // local function, and then a pass where we visit the local functions. If there's no // recursion or calls between the local functions, the starting state of the local // function should be stable and we don't need a second pass. if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) { // First visit everything else foreach (var stmt in block.Statements) { if (stmt.Kind != BoundKind.LocalFunctionStatement) { VisitStatement(stmt); } } // Now visit the local function bodies foreach (var stmt in block.Statements) { if (stmt is BoundLocalFunctionStatement localFunc) { VisitLocalFunctionStatement(localFunc); } } } else { foreach (var stmt in block.Statements) { VisitStatement(stmt); } } } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var localFunc = node.Symbol; var localFunctionState = GetOrCreateLocalFuncUsages(localFunc); // The starting state is the top state, but with captured // variables set according to Joining the state at all the // local function use sites var state = TopState(); var startingState = localFunctionState.StartingState; startingState.ForEach( (slot, variables) => { var symbol = variables[variables.RootSlot(slot)].Symbol; if (Symbol.IsCaptured(symbol, localFunc)) { state[slot] = startingState[slot]; } }, _variables); localFunctionState.Visited = true; AnalyzeLocalFunctionOrLambda( node, localFunc, state, delegateInvokeMethod: null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); SetInvalidResult(); return null; } private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) { _nestedFunctionVariables ??= PooledDictionary<MethodSymbol, Variables>.GetInstance(); if (!_nestedFunctionVariables.TryGetValue(lambdaOrLocalFunction, out var variables)) { variables = container.CreateNestedMethodScope(lambdaOrLocalFunction); _nestedFunctionVariables.Add(lambdaOrLocalFunction, variables); } Debug.Assert((object?)variables.Container == container); return variables; } private void AnalyzeLocalFunctionOrLambda( IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethod is object); Debug.Assert(!useDelegateInvokeReturnType || delegateInvokeMethod is object); var oldSymbol = this.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; var oldState = this.State; _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); this.State = state.CreateNestedMethodState(_variables); var previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? -1; try { var oldPending = SavePending(); EnterParameters(); var oldPending2 = SavePending(); // If this is an iterator, there's an implicit branch before the first statement // of the function where the enumerable is returned. if (lambdaOrFunctionSymbol.IsIterator) { PendingBranches.Add(new PendingBranch(null, this.State, null)); } VisitAlways(lambdaOrFunction.Body); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = oldSymbol; } protected override void VisitLocalFunctionUse( LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { // Do not use this overload in NullableWalker. Use the overload below instead. throw ExceptionUtilities.Unreachable; } private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) { Debug.Assert(!IsConditionalState); var localFunctionState = GetOrCreateLocalFuncUsages(symbol); var state = State.GetStateForVariables(localFunctionState.StartingState.Id); if (Join(ref localFunctionState.StartingState, ref state) && localFunctionState.Visited) { // If the starting state of the local function has changed and we've already visited // the local function, we need another pass stateChangedAfterUse = true; } } public override BoundNode? VisitDoStatement(BoundDoStatement node) { DeclareLocals(node.Locals); return base.VisitDoStatement(node); } public override BoundNode? VisitWhileStatement(BoundWhileStatement node) { DeclareLocals(node.Locals); return base.VisitWhileStatement(node); } public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) { Debug.Assert(!IsConditionalState); var receiver = withExpr.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); var resultType = withExpr.CloneMethod?.ReturnTypeWithAnnotations ?? ResultType.ToTypeWithAnnotations(compilation); var resultState = ApplyUnconditionalAnnotations(resultType.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); var resultSlot = GetOrCreatePlaceholderSlot(withExpr); // carry over the null state of members of 'receiver' to the result of the with-expression. TrackNullableStateForAssignment(receiver, resultType, resultSlot, resultState, MakeSlot(receiver)); // use the declared nullability of Clone() for the top-level nullability of the result of the with-expression. SetResult(withExpr, resultState, resultType); VisitObjectCreationInitializer(containingSymbol: null, resultSlot, withExpr.InitializerExpression, FlowAnalysisAnnotations.None); // Note: this does not account for the scenario where `Clone()` returns maybe-null and the with-expression has no initializers. // Tracking in https://github.com/dotnet/roslyn/issues/44759 return null; } public override BoundNode? VisitForStatement(BoundForStatement node) { DeclareLocals(node.OuterLocals); DeclareLocals(node.InnerLocals); return base.VisitForStatement(node); } public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); return base.VisitForEachStatement(node); } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { DeclareLocals(node.Locals); Visit(node.AwaitOpt); return base.VisitUsingStatement(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { Visit(node.AwaitOpt); return base.VisitUsingLocalDeclarations(node); } public override BoundNode? VisitFixedStatement(BoundFixedStatement node) { DeclareLocals(node.Locals); return base.VisitFixedStatement(node); } public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) { DeclareLocals(node.Locals); return base.VisitConstructorMethodBody(node); } private void DeclareLocal(LocalSymbol local) { if (local.DeclarationKind != LocalDeclarationKind.None) { int slot = GetOrCreateSlot(local); if (slot > 0) { this.State[slot] = GetDefaultState(ref this.State, slot); InheritDefaultState(GetDeclaredLocalResult(local).Type, slot); } } } private void DeclareLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { DeclareLocal(local); } } public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); // We need visit the optional arguments so that we can return nullability information // about them, but we don't want to communicate any information about anything underneath. // Additionally, tests like Scope_DeclaratorArguments_06 can have conditional expressions // in the optional arguments that can leave us in a split state, so we want to make sure // we are not in a conditional state after. Debug.Assert(!IsConditionalState); var oldDisable = _disableDiagnostics; _disableDiagnostics = true; var currentState = State; VisitAndUnsplitAll(node.ArgumentsOpt); _disableDiagnostics = oldDisable; SetState(currentState); if (node.DeclaredTypeOpt != null) { VisitTypeExpression(node.DeclaredTypeOpt); } var initializer = node.InitializerOpt; if (initializer is null) { return null; } TypeWithAnnotations type = local.TypeWithAnnotations; TypeWithState valueType; bool inferredType = node.InferredType; if (local.IsRef) { valueType = VisitRefExpression(initializer, type); } else { valueType = VisitOptionalImplicitConversion(initializer, targetTypeOpt: inferredType ? default : type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } if (inferredType) { if (valueType.HasNullType) { Debug.Assert(type.Type.IsErrorType()); valueType = type.ToTypeWithState(); } type = valueType.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local, type); if (node.DeclaredTypeOpt != null) { SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(type.ToTypeWithState(), type), true); } } TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer)); return null; } protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { Debug.Assert(!IsConditionalState); SetInvalidResult(); _ = base.VisitExpressionWithoutStackGuard(node); TypeWithState resultType = ResultType; #if DEBUG // Verify Visit method set _result. Debug.Assert((object?)resultType.Type != _invalidType.Type); Debug.Assert(AreCloseEnough(resultType.Type, node.Type)); #endif if (ShouldMakeNotNullRvalue(node)) { var result = resultType.WithNotNullState(); SetResult(node, result, LvalueResultType); } return null; } #if DEBUG // For asserts only. private static bool AreCloseEnough(TypeSymbol? typeA, TypeSymbol? typeB) { // https://github.com/dotnet/roslyn/issues/34993: We should be able to tighten this to ensure that we're actually always returning the same type, // not error if one is null or ignoring certain types if ((object?)typeA == typeB) { return true; } if (typeA is null || typeB is null) { return typeA?.IsErrorType() != false && typeB?.IsErrorType() != false; } return canIgnoreAnyType(typeA) || canIgnoreAnyType(typeB) || typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(type).Any(t => canIgnoreAnyType(t.Type)); } } private static bool AreCloseEnough(Symbol original, Symbol updated) { // When https://github.com/dotnet/roslyn/issues/38195 is fixed, this workaround needs to be removed if (original is ConstructedMethodSymbol || updated is ConstructedMethodSymbol) { return AreCloseEnough(original.OriginalDefinition, updated.OriginalDefinition); } return (original, updated) switch { (LambdaSymbol l, NamedTypeSymbol n) _ when n.IsDelegateType() => AreLambdaAndNewDelegateSimilar(l, n), (FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var oi } originalField, FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var ui } updatedField) => originalField.Type.Equals(updatedField.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) && oi == ui, _ => original.Equals(updated, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) }; } #endif private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) { var invokeMethod = n.DelegateInvokeMethod; return invokeMethod.Parameters.SequenceEqual(l.Parameters, (p1, p2) => p1.Type.Equals(p2.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) && invokeMethod.ReturnType.Equals(l.ReturnType, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames); } public override BoundNode? Visit(BoundNode? node) { return Visit(node, expressionIsRead: true); } private BoundNode VisitLValue(BoundNode node) { return Visit(node, expressionIsRead: false); } private BoundNode Visit(BoundNode? node, bool expressionIsRead) { bool originalExpressionIsRead = _expressionIsRead; _expressionIsRead = expressionIsRead; TakeIncrementalSnapshot(node); var result = base.Visit(node); _expressionIsRead = originalExpressionIsRead; return result; } protected override void VisitStatement(BoundStatement statement) { SetInvalidResult(); base.VisitStatement(statement); SetInvalidResult(); } public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { // This method is only involved in method inference with unbound lambdas. // The diagnostics on arguments are reported by VisitObjectCreationExpression. SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); return null; } private void VisitObjectOrDynamicObjectCreation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, BoundExpression? initializerOpt) { Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression || node.Kind == BoundKind.NewT); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var type = node.Type; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { var boundObjectCreationExpression = node as BoundObjectCreationExpression; var constructor = boundObjectCreationExpression?.Constructor; bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor(requireZeroInit: true) == true; if (EmptyStructTypeCache.IsTrackableStructType(type)) { var containingType = constructor?.ContainingType; if (containingType?.IsTupleType == true && !isDefaultValueTypeConstructor) { // new System.ValueTuple<T1, ..., TN>(e1, ..., eN) TrackNullableStateOfTupleElements(slot, containingType, arguments, argumentTypes, boundObjectCreationExpression!.ArgsToParamsOpt, useRestField: true); } else { InheritNullableStateOfTrackableStruct( type, slot, valueSlot: -1, isDefaultValue: isDefaultValueTypeConstructor); } } else if (type.IsNullableType()) { if (isDefaultValueTypeConstructor) { // a nullable value type created with its default constructor is by definition null resultState = NullableFlowState.MaybeNull; } else if (constructor?.ParameterCount == 1) { // if we deal with one-parameter ctor that takes underlying, then Value state is inferred from the argument. var parameterType = constructor.ParameterTypesWithAnnotations[0]; if (AreNullableAndUnderlyingTypes(type, parameterType.Type, out TypeWithAnnotations underlyingType)) { var operand = arguments[0]; int valueSlot = MakeSlot(operand); if (valueSlot > 0) { TrackNullableStateOfNullableValue(slot, type, operand, underlyingType.ToTypeWithState(), valueSlot); } } } } this.State[slot] = resultState; } } if (initializerOpt != null) { VisitObjectCreationInitializer(containingSymbol: null, slot, initializerOpt, leftAnnotations: FlowAnalysisAnnotations.None); } SetResultType(node, TypeWithState.Create(type, resultState)); } private void VisitObjectCreationInitializer(Symbol? containingSymbol, int containingSlot, BoundExpression node, FlowAnalysisAnnotations leftAnnotations) { TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: checkImplicitReceiver(objectInitializer); foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: VisitObjectElementInitializer(containingSlot, (BoundAssignmentOperator)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: checkImplicitReceiver(collectionInitializer); foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: Debug.Assert(containingSymbol is object); if (containingSymbol is object) { var type = ApplyLValueAnnotations(containingSymbol.GetTypeOrReturnType(), leftAnnotations); TypeWithState resultType = VisitOptionalImplicitConversion(node, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment); TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node)); } break; } void checkImplicitReceiver(BoundObjectInitializerExpressionBase node) { if (containingSlot >= 0 && !node.Initializers.IsEmpty) { if (!node.Type.IsValueType && State[containingSlot].MayBeNull()) { if (containingSymbol is null) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, node.Syntax); } else { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, node.Syntax, containingSymbol); } } } } } private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOperator node) { TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { var objectInitializer = (BoundObjectInitializerMember)left; TakeIncrementalSnapshot(left); var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) { int slot = (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); VisitObjectCreationInitializer(symbol, slot, node.Right, GetLValueAnnotations(node.Left)); // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); } break; default: Visit(node); break; } } private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { Debug.Assert(node.ImplicitReceiverOpt.Kind == BoundKind.ObjectOrCollectionValuePlaceholder); SetAnalyzedNullability(node.ImplicitReceiverOpt, new VisitResult(node.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); } SetUnknownResultNullability(node); SetUpdatedSymbol(node, node.AddMethod, reinferredMethod); } private void SetNotNullResult(BoundExpression node) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); } /// <summary> /// Returns true if the type is a struct with no fields or properties. /// </summary> protected override bool IsEmptyStructType(TypeSymbol type) { if (type.TypeKind != TypeKind.Struct) { return false; } // EmptyStructTypeCache.IsEmptyStructType() returns false // if there are non-cyclic fields. if (!_emptyStructTypeCache.IsEmptyStructType(type)) { return false; } if (type.SpecialType != SpecialType.None) { return true; } var members = ((NamedTypeSymbol)type).GetMembersUnordered(); // EmptyStructTypeCache.IsEmptyStructType() returned true. If there are fields, // at least one of those fields must be cyclic, so treat the type as empty. if (members.Any(m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(m => m.Kind == SymbolKind.Property)) { return false; } return true; } private int GetOrCreatePlaceholderSlot(BoundExpression node) { Debug.Assert(node.Type is object); if (IsEmptyStructType(node.Type)) { return -1; } return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); } private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) { _placeholderLocalsOpt ??= PooledDictionary<object, PlaceholderLocal>.GetInstance(); if (!_placeholderLocalsOpt.TryGetValue(identifier, out var placeholder)) { placeholder = new PlaceholderLocal(CurrentSymbol, identifier, type); _placeholderLocalsOpt.Add(identifier, placeholder); } Debug.Assert((object)placeholder != null); return GetOrCreateSlot(placeholder, forceSlotEvenIfEmpty: true); } public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { Debug.Assert(!IsConditionalState); Debug.Assert(node.Type.IsAnonymousType); var anonymousType = (NamedTypeSymbol)node.Type; var arguments = node.Arguments; var argumentTypes = arguments.SelectAsArray((arg, self) => self.VisitRvalueWithState(arg), this); var argumentsWithAnnotations = argumentTypes.SelectAsArray(arg => arg.ToTypeWithAnnotations(compilation)); if (argumentsWithAnnotations.All(argType => argType.HasType)) { anonymousType = AnonymousTypeManager.ConstructAnonymousTypeSymbol(anonymousType, argumentsWithAnnotations); int receiverSlot = GetOrCreatePlaceholderSlot(node); int currentDeclarationIndex = 0; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var argumentType = argumentTypes[i]; var property = AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, i); if (property.Type.SpecialType != SpecialType.System_Void) { // A void element results in an error type in the anonymous type but not in the property's container! // To avoid failing an assertion later, we skip them. var slot = GetOrCreateSlot(property, receiverSlot); TrackNullableStateForAssignment(argument, property.TypeWithAnnotations, slot, argumentType, MakeSlot(argument)); var currentDeclaration = getDeclaration(node, property, ref currentDeclarationIndex); if (currentDeclaration is object) { TakeIncrementalSnapshot(currentDeclaration); SetAnalyzedNullability(currentDeclaration, new VisitResult(argumentType, property.TypeWithAnnotations)); } } } } SetResultType(node, TypeWithState.Create(anonymousType, NullableFlowState.NotNull)); return null; static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression node, PropertySymbol currentProperty, ref int currentDeclarationIndex) { if (currentDeclarationIndex >= node.Declarations.Length) { return null; } var currentDeclaration = node.Declarations[currentDeclarationIndex]; if (currentDeclaration.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) { currentDeclarationIndex++; return currentDeclaration; } return null; } } public override BoundNode? VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } TakeIncrementalSnapshot(initialization); var expressions = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length); GetArrayElements(initialization, expressions); int n = expressions.Count; // Consider recording in the BoundArrayCreation // whether the array was implicitly typed, rather than relying on syntax. bool isInferred = node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression; var arrayType = (ArrayTypeSymbol)node.Type; var elementType = arrayType.ElementTypeWithAnnotations; if (!isInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(n); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); foreach (var expression in expressions) { // collect expressions, conversions and result types (BoundExpression expressionNoConversion, Conversion conversion) = RemoveConversion(expression, includeExplicitConversions: false); expressionsNoConversions.Add(expressionNoConversion); conversions.Add(conversion); SnapshotWalkerThroughConversionGroup(expression, expressionNoConversion); var resultType = VisitRvalueWithState(expressionNoConversion); resultTypes.Add(resultType); placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, resultType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!node.HasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo); } TypeWithAnnotations inferredType = (bestType is null) ? elementType.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(bestType); if (bestType is object) { // Convert elements to best type to determine element top-level nullability and to report nested nullability warnings for (int i = 0; i < n; i++) { var expressionNoConversion = expressionsNoConversions[i]; var expression = GetConversionIfApplicable(expressions[i], expressionNoConversion); resultTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false); } // Set top-level nullability on inferred element type var elementState = BestTypeInferrer.GetNullableState(resultTypes); inferredType = TypeWithState.Create(inferredType.Type, elementState).ToTypeWithAnnotations(compilation); for (int i = 0; i < n; i++) { // Report top-level warnings _ = VisitConversion(conversionOpt: null, conversionOperand: expressionsNoConversions[i], Conversion.Identity, targetTypeWithNullability: inferredType, operandType: resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false); } } else { // We need to ensure that we're tracking the inferred type with nullability of any conversions that // were stripped off. for (int i = 0; i < n; i++) { TrackAnalyzedNullabilityThroughConversionGroup(inferredType.ToTypeWithState(), expressions[i] as BoundConversion, expressionsNoConversions[i]); } } expressionsNoConversions.Free(); conversions.Free(); resultTypes.Free(); arrayType = arrayType.WithElementType(inferredType); } expressions.Free(); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } /// <summary> /// Applies analysis similar to <see cref="VisitArrayCreation"/>. /// The expressions returned from a lambda are not converted though, so we'll have to classify fresh conversions. /// Note: even if some conversions fail, we'll proceed to infer top-level nullability. That is reasonable in common cases. /// </summary> internal static TypeWithAnnotations BestTypeForLambdaReturns( ArrayBuilder<(BoundExpression, TypeWithAnnotations)> returns, Binder binder, BoundNode node, Conversions conversions) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: null, returnTypesOpt: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); int n = returns.Count; var resultTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); var placeholdersBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var (returnExpr, resultType) = returns[i]; resultTypes.Add(resultType); placeholdersBuilder.Add(CreatePlaceholderIfNecessary(returnExpr, resultType)); } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var placeholders = placeholdersBuilder.ToImmutableAndFree(); TypeSymbol? bestType = BestTypeInferrer.InferBestType(placeholders, walker._conversions, ref discardedUseSiteInfo); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); ConversionsBase conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, ref discardedUseSiteInfo); resultTypes[i] = walker.VisitConversion(conversionOpt: null, placeholder, conversion, bestTypeWithObliviousAnnotation, resultTypes[i].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, reportRemainingWarnings: false, reportTopLevelWarnings: false).ToTypeWithAnnotations(binder.Compilation); } // Set top-level nullability on inferred type inferredType = TypeWithAnnotations.Create(bestType, BestTypeInferrer.GetNullableAnnotation(resultTypes)); } else { inferredType = default; } resultTypes.Free(); walker.Free(); return inferredType; } private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { GetArrayElements((BoundArrayInitialization)child, builder); } else { builder.Add(child); } } } public override BoundNode? VisitArrayAccess(BoundArrayAccess node) { Debug.Assert(!IsConditionalState); Visit(node.Expression); Debug.Assert(!IsConditionalState); Debug.Assert(!node.Expression.Type!.IsValueType); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(node.Expression); var type = ResultType.Type as ArrayTypeSymbol; foreach (var i in node.Indices) { VisitRvalue(i); } TypeWithAnnotations result; if (node.Indices.Length == 1 && TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything2)) { result = TypeWithAnnotations.Create(type); } else { result = type?.ElementTypeWithAnnotations ?? default; } SetLvalueResultType(node, result); return null; } private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) { NullableFlowState resultState = NullableFlowState.NotNull; if (operatorKind.IsUserDefined()) { if (methodOpt?.ParameterCount == 2) { if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); } var resultTypeWithState = GetReturnTypeWithState(methodOpt); if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) { resultTypeWithState = resultTypeWithState.WithNotNullState(); } return resultTypeWithState; } } else if (!operatorKind.IsDynamic() && !resultType.IsValueType) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.DelegateCombination: resultState = leftType.State.Meet(rightType.State); break; case BinaryOperatorKind.DelegateRemoval: resultState = NullableFlowState.MaybeNull; // Delegate removal can produce null. break; default: resultState = NullableFlowState.NotNull; break; } } if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { resultState = leftType.State.Join(rightType.State); } return TypeWithState.Create(resultType, resultState); } protected override void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); var (leftOperand, leftConversion) = RemoveConversion(binary.Left, includeExplicitConversions: false); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(leftOperand, out var conditionalStateWhenNotNull) && CanPropagateStateWhenNotNull(leftConversion) && binary.OperatorKind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // Consider the following two scenarios: // `a?.b(x = new object()) == c.d(x = null)` // `x` is maybe-null after expression // `a?.b(x = null) == c.d(x = new object())` // `x` is not-null after expression // In this scenario, we visit the RHS twice: // (1) Once using the single "stateWhenNotNull" after the LHS, in order to update the "stateWhenNotNull" with the effects of the RHS // (2) Once using the "worst case" state after the LHS for diagnostics and public API // After the two visits of the RHS, we may set a conditional state using the state after (1) as the StateWhenTrue and the state after (2) as the StateWhenFalse. // Depending on whether `==` or `!=` was used, and depending on the value of the RHS, we may then swap the StateWhenTrue with the StateWhenFalse. var oldDisableDiagnostics = _disableDiagnostics; _disableDiagnostics = true; var stateAfterLeft = this.State; SetState(getUnconditionalStateWhenNotNull(rightOperand, conditionalStateWhenNotNull)); VisitRvalue(rightOperand); var stateWhenNotNull = this.State; _disableDiagnostics = oldDisableDiagnostics; // Now visit the right side for public API and diagnostics using the worst-case state from the LHS. // Note that we do this visit last to try and make sure that the "visit for public API" overwrites walker state recorded during previous visits where possible. SetState(stateAfterLeft); var rightType = VisitRvalueWithState(rightOperand); ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); if (isKnownNullOrNotNull(rightOperand, rightType)) { var isNullConstant = rightOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } if (stack.Count == 0) { return; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } while (true) { if (!learnFromConditionalAccessOrBoolConstant()) { Unsplit(); // VisitRvalue does this UseRvalueOnly(leftOperand); // drop lvalue part AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); } if (stack.Count == 0) { break; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState resultType) { return resultType.State.IsNotNull() || expr.ConstantValue is object; } LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) { LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else if (isEquals(binary) && otherOperand.ConstantValue is { IsBoolean: true, BooleanValue: var boolValue }) { // can preserve conditional state from `.TryGetValue` in `dict?.TryGetValue(key, out value) == true`, // but not in `dict?.TryGetValue(key, out value) != false` stateWhenNotNull = boolValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } return stateWhenNotNull; } // Returns true if `binary.Right` was visited by the call. bool learnFromConditionalAccessOrBoolConstant() { if (binary.OperatorKind.Operator() is not (BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual)) { return false; } var leftResult = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // `true == a?.b(out x)` if (isKnownNullOrNotNull(leftOperand, leftResult) && CanPropagateStateWhenNotNull(rightConversion) && TryVisitConditionalAccess(rightOperand, out var conditionalStateWhenNotNull)) { ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftResult, rightOperand, rightConversion, rightType: ResultType, binary); var stateWhenNotNull = getUnconditionalStateWhenNotNull(leftOperand, conditionalStateWhenNotNull); var isNullConstant = leftOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // can only learn from a bool constant operand here if it's using the built in `bool operator ==(bool left, bool right)` if (binary.OperatorKind.IsUserDefined()) { return false; } // `(x != null) == true` if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); // record result for the right SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); } // `true == (x != null)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { return false; } // record result for the binary Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); return true; } } private void ReinferBinaryOperatorAndSetResult( BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); // At this point, State.Reachable may be false for // invalid code such as `s + throw new Exception()`. var method = binary.Method; if (binary.OperatorKind.IsUserDefined() && method?.ParameterCount == 2) { // Update method based on inferred operand type. TypeSymbol methodContainer = method.ContainingType; bool isLifted = binary.OperatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); TypeSymbol? asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type); if (asMemberOfType is object) { method = (MethodSymbol)AsMemberOfType(asMemberOfType, method); } // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameters = method.Parameters; visitOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { TypeWithAnnotations targetTypeWithNullability = parameter.TypeWithAnnotations; if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } _ = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); } } else { // Assume this is a built-in operator in which case the parameter types are unannotated. visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) { if (expr.Type is null) { Debug.Assert(operand == expr); } else { _ = VisitConversion( expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); } } } Debug.Assert(!IsConditionalState); // For nested binary operators, this can be the only time they're visited due to explicit stack used in AbstractFlowPass.VisitBinaryOperator, // so we need to set the flow-analyzed type here. var inferredResult = InferResultNullability(binary.OperatorKind, method, binary.Type, leftType, rightType); SetResult(binary, inferredResult, inferredResult.ToTypeWithAnnotations(compilation)); TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType) { if (derivedType is null) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, ref discardedUseSiteInfo); if (conversion.Exists && !conversion.IsExplicit) { return derivedType; } return null; } } private void AfterLeftChildHasBeenVisited( BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); VisitRvalue(rightOperand); var rightType = ResultType; ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); BinaryOperatorKind op = binary.OperatorKind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { // learn from null constant BoundExpression? operandComparedToNull = null; if (binary.Right.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Left; } else if (binary.Left.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Right; } if (operandComparedToNull != null) { // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c. bool nonNullCase = op != BinaryOperatorKind.Equal; // true represents WhenTrue splitAndLearnFromNonNullTest(operandComparedToNull, whenTrue: nonNullCase); // `x == null` and `x != null` are pure null tests so update the null-state in the alternative branch too LearnFromNullTest(operandComparedToNull, ref nonNullCase ? ref StateWhenFalse : ref StateWhenTrue); return; } } // learn from comparison between non-null and maybe-null, possibly updating maybe-null to non-null BoundExpression? operandComparedToNonNull = null; if (leftType.IsNotNull && rightType.MayBeNull) { operandComparedToNonNull = binary.Right; } else if (rightType.IsNotNull && leftType.MayBeNull) { operandComparedToNonNull = binary.Left; } if (operandComparedToNonNull != null) { switch (op) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: true); return; case BinaryOperatorKind.NotEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: false); return; }; } void splitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) { var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(operandComparedToNonNull, slotBuilder); if (slotBuilder.Count != 0) { Split(); ref LocalState stateToUpdate = ref whenTrue ? ref this.StateWhenTrue : ref this.StateWhenFalse; MarkSlotsAsNotNull(slotBuilder, ref stateToUpdate); } slotBuilder.Free(); } } protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) { var result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); SetNotNullResult(node); return result; } protected override BoundBinaryOperator? PushBinaryOperatorInterpolatedStringChildren(BoundBinaryOperator node, ArrayBuilder<BoundInterpolatedString> stack) { var result = base.PushBinaryOperatorInterpolatedStringChildren(node, stack); SetNotNullResult(node); return result; } /// <summary> /// If we learn that the operand is non-null, we can infer that certain /// sub-expressions were also non-null. /// Get all nested conditional slots for those sub-expressions. For example in a?.b?.c we'll set a, b, and c. /// Only returns slots for tracked expressions. /// </summary> /// <remarks>https://github.com/dotnet/roslyn/issues/53397 This method should potentially be removed.</remarks> private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder<int> slotBuilder) { Debug.Assert(operand != null); var previousConditionalAccessSlot = _lastConditionalAccessSlot; try { while (true) { // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree, // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot // for, nothing underneath is trackable and we bail at that point. Example: // // a?.GetB()?.C // a is a field, GetB is a method, and C is a property // // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because // fields have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll // return an array with just the slot for a. int slot; switch (operand.Kind) { case BoundKind.Conversion: // https://github.com/dotnet/roslyn/issues/33879 Detect when conversion has a nullable operand operand = ((BoundConversion)operand).Operand; continue; case BoundKind.AsOperator: operand = ((BoundAsOperator)operand).Operand; continue; case BoundKind.ConditionalAccess: var conditional = (BoundConditionalAccess)operand; GetSlotsToMarkAsNotNullable(conditional.Receiver, slotBuilder); slot = MakeSlot(conditional.Receiver); if (slot > 0) { // We need to continue the walk regardless of whether the receiver should be updated. var receiverType = conditional.Receiver.Type!; if (receiverType.IsNullableType()) slot = GetNullableOfTValueSlot(receiverType, slot, out _); } if (slot > 0) { // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers // until it gets to the BoundConditionalReceiver associated with this node. In our override // of MakeSlot, we substitute this slot when we encounter a BoundConditionalReceiver, and reset the // _lastConditionalAccess field. _lastConditionalAccessSlot = slot; operand = conditional.AccessExpression; continue; } // If there's no slot for this receiver, there cannot be another slot for any of the remaining // access expressions. break; default: // Attempt to create a slot for the current thing. If there were any more conditional accesses, // they would have been on top, so this is the last thing we need to specially handle. // https://github.com/dotnet/roslyn/issues/33879 When we handle unconditional access survival (ie after // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether // we need more special handling here slot = MakeSlot(operand); if (slot > 0 && PossiblyNullableType(operand.Type)) { slotBuilder.Add(slot); } break; } return; } } finally { _lastConditionalAccessSlot = previousConditionalAccessSlot; } } private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) => operandType?.CanContainNull() == true; private static void MarkSlotsAsNotNull(ArrayBuilder<int> slots, ref LocalState stateToUpdate) { foreach (int slot in slots) { stateToUpdate[slot] = NullableFlowState.NotNull; } } private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) { if (expression.Kind == BoundKind.AwaitableValuePlaceholder) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue((BoundAwaitableValuePlaceholder)expression, out var value)) { expression = value.AwaitableExpression; } else { return; } } var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(expression, slotBuilder); MarkSlotsAsNotNull(slotBuilder, ref state); slotBuilder.Free(); } private void LearnFromNonNullTest(int slot, ref LocalState state) { state[slot] = NullableFlowState.NotNull; } private void LearnFromNullTest(BoundExpression expression, ref LocalState state) { // nothing to learn about a constant if (expression.ConstantValue != null) return; // We should not blindly strip conversions here. Tracked by https://github.com/dotnet/roslyn/issues/36164 var expressionWithoutConversion = RemoveConversion(expression, includeExplicitConversions: true).expression; var slot = MakeSlot(expressionWithoutConversion); // Since we know for sure the slot is null (we just tested it), we know that dependent slots are not // reachable and therefore can be treated as not null. However, we have not computed the proper // (inferred) type for the expression, so we cannot compute the correct symbols for the member slots here // (using the incorrect symbols would result in computing an incorrect default state for them). // Therefore we do not mark dependent slots not null. See https://github.com/dotnet/roslyn/issues/39624 LearnFromNullTest(slot, expressionWithoutConversion.Type, ref state, markDependentSlotsNotNull: false); } private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) { if (slot > 0 && PossiblyNullableType(expressionType)) { if (state[slot] == NullableFlowState.NotNull) { // Note: We leave a MaybeDefault state as-is state[slot] = NullableFlowState.MaybeNull; } if (markDependentSlotsNotNull) { MarkDependentSlotsNotNull(slot, expressionType, ref state); } } } // If we know for sure that a slot contains a null value, then we know for sure that dependent slots // are "unreachable" so we might as well treat them as not null. That way when this state is merged // with another state, those dependent states won't pollute values from the other state. private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) { if (depth <= 0) return; foreach (var member in getMembers(expressionType)) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var containingType = this._symbol?.ContainingType; if ((member is PropertySymbol { IsIndexedProperty: false } || member.Kind == SymbolKind.Field) && member.RequiresInstanceReceiver() && (containingType is null || AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))) { int childSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); if (childSlot > 0) { state[childSlot] = NullableFlowState.NotNull; MarkDependentSlotsNotNull(childSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); } } } static IEnumerable<Symbol> getMembers(TypeSymbol type) { // First, return the direct members foreach (var member in type.GetMembers()) yield return member; // All types inherit members from their effective bases for (NamedTypeSymbol baseType = effectiveBase(type); !(baseType is null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) foreach (var member in baseType.GetMembers()) yield return member; // Interfaces and type parameters inherit from their effective interfaces foreach (NamedTypeSymbol interfaceType in inheritedInterfaces(type)) foreach (var member in interfaceType.GetMembers()) yield return member; yield break; static NamedTypeSymbol effectiveBase(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.EffectiveBaseClassNoUseSiteDiagnostics, var t => t.BaseTypeNoUseSiteDiagnostics, }; static ImmutableArray<NamedTypeSymbol> inheritedInterfaces(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.AllEffectiveInterfacesNoUseSiteDiagnostics, { TypeKind: TypeKind.Interface } => type.AllInterfacesNoUseSiteDiagnostics, _ => ImmutableArray<NamedTypeSymbol>.Empty, }; } } private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) { while (possiblyConversion.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)possiblyConversion; switch (conversion.ConversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: possiblyConversion = conversion.Operand; break; default: return possiblyConversion; } } return possiblyConversion; } public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; int leftSlot = MakeSlot(leftOperand); TypeWithAnnotations targetType = VisitLvalueWithAnnotations(leftOperand); var leftState = this.State.Clone(); LearnFromNonNullTest(leftOperand, ref leftState); LearnFromNullTest(leftOperand, ref this.State); if (node.IsNullableValueTypeAssignment) { targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); } TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand, targetType), trackMembers: false, AssignmentKind.Assignment); TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand)); Join(ref this.State, ref leftState); TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State); SetResultType(node, resultType); return null; } public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { Debug.Assert(!IsConditionalState); BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; if (IsConstantNull(leftOperand)) { VisitRvalue(leftOperand); Visit(rightOperand); var rightUnconditionalResult = ResultType; // Should be able to use rightResult for the result of the operator but // binding may have generated a different result type in the case of errors. SetResultType(node, TypeWithState.Create(node.Type, rightUnconditionalResult.State)); return null; } VisitPossibleConditionalAccess(leftOperand, out var whenNotNull); TypeWithState leftResult = ResultType; Unsplit(); LearnFromNullTest(leftOperand, ref this.State); bool leftIsConstant = leftOperand.ConstantValue != null; if (leftIsConstant) { SetUnreachable(); } Visit(rightOperand); TypeWithState rightResult = ResultType; Join(ref whenNotNull); var leftResultType = leftResult.Type; var rightResultType = rightResult.Type; var (resultType, leftState) = node.OperatorResultKind switch { BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightDynamicType => (rightResultType!, NullableFlowState.NotNull), _ => throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind), }; SetResultType(node, TypeWithState.Create(resultType, rightResult.State.Join(leftState))); return null; (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) { Debug.Assert(rightType is object); // If there was an identity conversion between the two operands (in short, if there // is no implicit conversion on the right operand), then check nullable conversions // in both directions since it's possible the right operand is the better result type. if ((node.RightOperand as BoundConversion)?.ExplicitCastInCode != false && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true); Debug.Assert(!conversion.IsUserDefined); return (leftType, NullableFlowState.NotNull); } (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) { var conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true); if (conversion.IsUserDefined) { var conversionResult = VisitConversion( conversionOpt: null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), // When considering the conversion on the left node, it can only occur in the case where the underlying // execution returned non-null TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: false); Debug.Assert(conversionResult.Type is not null); return (conversionResult.Type!, conversionResult.State); } return (rightType, NullableFlowState.NotNull); } } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { var (operand, conversion) = RemoveConversion(node, includeExplicitConversions: true); if (operand is not BoundConditionalAccess access || !CanPropagateStateWhenNotNull(conversion)) { stateWhenNotNull = default; return false; } Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); if (node is BoundConversion boundConversion) { var operandType = ResultType; TypeWithAnnotations explicitType = boundConversion.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(boundConversion.Type); Debug.Assert(targetType.HasType); var result = VisitConversion(boundConversion, access, conversion, targetType, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, assignmentKind: AssignmentKind.Assignment); SetResultType(boundConversion, result); } Debug.Assert(!IsConditionalState); return true; } /// <summary> /// Unconditionally visits an expression and returns the "state when not null" for the expression. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } // in case we *didn't* have a conditional access, the only thing we learn in the "state when not null" // is that the top-level expression was non-null. Visit(node); stateWhenNotNull = PossiblyConditionalState.Create(this); (node, _) = RemoveConversion(node, includeExplicitConversions: true); var slot = MakeSlot(node); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenTrue); LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenFalse); } else { LearnFromNonNullTest(slot, ref stateWhenNotNull.State); } } return false; } private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) { Debug.Assert(!IsConditionalState); var receiver = node.Receiver; // handle scenarios like `(a?.b)?.c()` VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); Unsplit(); _currentConditionalReceiverVisitResult = _visitResult; var previousConditionalAccessSlot = _lastConditionalAccessSlot; if (receiver.ConstantValue is { IsNull: false }) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); } else { var savedState = this.State.Clone(); if (IsConstantNull(receiver)) { SetUnreachable(); _lastConditionalAccessSlot = -1; } else { // In the when-null branch, the receiver is known to be maybe-null. // In the other branch, the receiver is known to be non-null. LearnFromNullTest(receiver, ref savedState); makeAndAdjustReceiverSlot(receiver); SetPossiblyConditionalState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); VisitRvalue(innerCondAccess.Receiver); _currentConditionalReceiverVisitResult = _visitResult; makeAndAdjustReceiverSlot(innerCondAccess.Receiver); // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); Visit(expr); expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // The resulting nullability of each nested conditional access is the same as the resulting nullability of the rightmost access. SetAnalyzedNullability(innerCondAccess, _visitResult); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); var slot = MakeSlot(expr); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref StateWhenTrue); LearnFromNonNullTest(slot, ref StateWhenFalse); } else { LearnFromNonNullTest(slot, ref State); } } stateWhenNotNull = PossiblyConditionalState.Create(this); Unsplit(); Join(ref this.State, ref savedState); } var accessTypeWithAnnotations = LvalueResultType; TypeSymbol accessType = accessTypeWithAnnotations.Type; var oldType = node.Type; var resultType = oldType.IsVoidType() || oldType.IsErrorType() ? oldType : oldType.IsNullableType() && !accessType.IsNullableType() ? MakeNullableOf(accessTypeWithAnnotations) : accessType; // Per LDM 2019-02-13 decision, the result of a conditional access "may be null" even if // both the receiver and right-hand-side are believed not to be null. SetResultType(node, TypeWithState.Create(resultType, NullableFlowState.MaybeDefault)); _currentConditionalReceiverVisitResult = default; _lastConditionalAccessSlot = previousConditionalAccessSlot; void makeAndAdjustReceiverSlot(BoundExpression receiver) { var slot = MakeSlot(receiver); if (slot > -1) LearnFromNonNullTest(slot, ref State); // given `a?.b()`, when `a` is a nullable value type, // the conditional receiver for `?.b()` must be linked to `a.Value`, not to `a`. if (slot > 0 && receiver.Type?.IsNullableType() == true) slot = GetNullableOfTValueSlot(receiver.Type, slot, out _); _lastConditionalAccessSlot = slot; } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, out _); return null; } protected override BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; TypeWithState consequenceRValue; TypeWithState alternativeRValue; if (isRef) { TypeWithAnnotations consequenceLValue; TypeWithAnnotations alternativeLValue; (consequenceLValue, consequenceRValue) = visitConditionalRefOperand(consequenceState, originalConsequence); consequenceState = this.State; (alternativeLValue, alternativeRValue) = visitConditionalRefOperand(alternativeState, originalAlternative); Join(ref this.State, ref consequenceState); TypeSymbol? refResultType = node.Type?.SetUnknownNullabilityForReferenceTypes(); if (IsNullabilityMismatch(consequenceLValue, alternativeLValue)) { // l-value types must match ReportNullabilityMismatchInAssignment(node.Syntax, consequenceLValue, alternativeLValue); } else if (!node.HasErrors) { refResultType = consequenceRValue.Type!.MergeEquivalentTypes(alternativeRValue.Type, VarianceKind.None); } var lValueAnnotation = consequenceLValue.NullableAnnotation.EnsureCompatible(alternativeLValue.NullableAnnotation); var rValueState = consequenceRValue.State.Join(alternativeRValue.State); SetResult(node, TypeWithState.Create(refResultType, rValueState), TypeWithAnnotations.Create(refResultType, lValueAnnotation)); return null; } (var consequence, var consequenceConversion, consequenceRValue) = visitConditionalOperand(consequenceState, originalConsequence); var consequenceConditionalState = PossiblyConditionalState.Create(this); consequenceState = CloneAndUnsplit(ref consequenceConditionalState); var consequenceEndReachable = consequenceState.Reachable; (var alternative, var alternativeConversion, alternativeRValue) = visitConditionalOperand(alternativeState, originalAlternative); var alternativeConditionalState = PossiblyConditionalState.Create(this); alternativeState = CloneAndUnsplit(ref alternativeConditionalState); var alternativeEndReachable = alternativeState.Reachable; SetPossiblyConditionalState(in consequenceConditionalState); Join(ref alternativeConditionalState); TypeSymbol? resultType; bool wasTargetTyped = node is BoundConditionalOperator { WasTargetTyped: true }; if (node.HasErrors || wasTargetTyped) { resultType = null; } else { // Determine nested nullability using BestTypeInferrer. // If a branch is unreachable, we could use the nested nullability of the other // branch, but that requires using the nullability of the branch as it applies to the // target type. For instance, the result of the conditional in the following should // be `IEnumerable<object>` not `object[]`: // object[] a = ...; // IEnumerable<object?> b = ...; // var c = true ? a : b; BoundExpression consequencePlaceholder = CreatePlaceholderIfNecessary(consequence, consequenceRValue.ToTypeWithAnnotations(compilation)); BoundExpression alternativePlaceholder = CreatePlaceholderIfNecessary(alternative, alternativeRValue.ToTypeWithAnnotations(compilation)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(consequencePlaceholder, alternativePlaceholder, _conversions, out _, ref discardedUseSiteInfo); } resultType ??= node.Type?.SetUnknownNullabilityForReferenceTypes(); NullableFlowState resultState; if (!wasTargetTyped) { if (resultType is null) { // This can happen when we're inferring the return type of a lambda. For this case, we don't need to do any work, // the unconverted conditional operator can't contribute info. The conversion that should be on top of this // can add or remove nullability, and nested nodes aren't being publicly exposed by the semantic model. Debug.Assert(node is BoundUnconvertedConditionalOperator); Debug.Assert(_returnTypesOpt is not null); resultState = default; } else { var resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); TypeWithState convertedConsequenceResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalConsequence, consequence, consequenceConversion, resultTypeWithAnnotations, consequenceRValue, consequenceState, consequenceEndReachable); TypeWithState convertedAlternativeResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalAlternative, alternative, alternativeConversion, resultTypeWithAnnotations, alternativeRValue, alternativeState, alternativeEndReachable); resultState = convertedConsequenceResult.State.Join(convertedAlternativeResult.State); } } else { resultState = consequenceRValue.State.Join(alternativeRValue.State); ConditionalInfoForConversion.Add(node, ImmutableArray.Create( (consequenceState, consequenceRValue, consequenceEndReachable), (alternativeState, alternativeRValue, alternativeEndReachable))); } SetResultType(node, TypeWithState.Create(resultType, resultState)); return null; (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) { Conversion conversion; SetState(state); Debug.Assert(!isRef); BoundExpression operandNoConversion; (operandNoConversion, conversion) = RemoveConversion(operand, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(operand, operandNoConversion); Visit(operandNoConversion); return (operandNoConversion, conversion, ResultType); } (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) { SetState(state); Debug.Assert(isRef); TypeWithAnnotations lValueType = VisitLvalueWithAnnotations(operand); return (lValueType, ResultType); } } private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult( BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) { var savedState = this.State; this.State = state; bool previousDisabledDiagnostics = _disableDiagnostics; // If the node is not reachable, then we're only visiting to get // nullability information for the public API, and not to produce diagnostics. // Disable diagnostics, and return default for the resulting state // to indicate that warnings were suppressed. if (!isReachable) { _disableDiagnostics = true; } var resultType = VisitConversion( GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false); if (!isReachable) { resultType = default; _disableDiagnostics = previousDisabledDiagnostics; } this.State = savedState; return resultType; } private bool IsReachable() => this.IsConditionalState ? (this.StateWhenTrue.Reachable || this.StateWhenFalse.Reachable) : this.State.Reachable; /// <summary> /// Placeholders are bound expressions with type and state. /// But for typeless expressions (such as `null` or `(null, null)` we hold onto the original bound expression, /// as it will be useful for conversions from expression. /// </summary> private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) { return !type.HasType ? expr : new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); } public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) { var rvalueType = _currentConditionalReceiverVisitResult.RValueType.Type; if (rvalueType?.IsNullableType() == true) { rvalueType = rvalueType.GetNullableUnderlyingType(); } SetResultType(node, TypeWithState.Create(rvalueType, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitCall(BoundCall node) { // Note: we analyze even omitted calls TypeWithState receiverType = VisitCallReceiver(node); ReinferMethodAndVisitArguments(node, receiverType); return null; } private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType) { var method = node.Method; ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt; if (!receiverType.HasNullType) { // Update method based on inferred receiver type. method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } ImmutableArray<VisitArgumentResult> results; bool returnNotNull; (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); LearnFromEqualsMethod(method, node, receiverType, results); var returnState = GetReturnTypeWithState(method); if (returnNotNull) { returnState = returnState.WithNotNullState(); } SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray<VisitArgumentResult> results) { // easy out var parameterCount = method.ParameterCount; var arguments = node.Arguments; if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || method.MethodKind != MethodKind.Ordinary || method.ReturnType.SpecialType != SpecialType.System_Boolean || (method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__Equals).Name && method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__ReferenceEquals).Name && !anyOverriddenMethodHasExplicitImplementation(method))) { return; } var isStaticEqualsMethod = method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__EqualsObjectObject)) || method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals)); if (isStaticEqualsMethod || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_Collections_Generic_IEqualityComparer_T__Equals)) { Debug.Assert(arguments.Length == 2); learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); return; } var isObjectEqualsMethodOrOverride = method.GetLeastOverriddenMethod(accessingTypeOpt: null) .Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals)); if (node.ReceiverOpt is BoundExpression receiver && (isObjectEqualsMethodOrOverride || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_IEquatable_T__Equals))) { Debug.Assert(arguments.Length == 1); learnFromEqualsMethodArguments(receiver, receiverType, arguments[0], results[0].RValueType); return; } static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol method) { for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.IsExplicitInterfaceImplementation) { return true; } } return false; } static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol method, TypeSymbol? receiverType, WellKnownMember wellKnownMember) { var wellKnownMethod = (MethodSymbol?)compilation.GetWellKnownTypeMember(wellKnownMember); if (wellKnownMethod is null || receiverType is null) { return false; } var wellKnownType = wellKnownMethod.ContainingType; var parameterType = method.Parameters[0].TypeWithAnnotations; var constructedType = wellKnownType.Construct(ImmutableArray.Create(parameterType)); var constructedMethod = wellKnownMethod.AsMember(constructedType); // FindImplementationForInterfaceMember doesn't check if this method is itself the interface method we're looking for if (constructedMethod.Equals(method)) { return true; } // check whether 'method', when called on this receiver, is an implementation of 'constructedMethod'. for (var baseType = receiverType; baseType is object && method is object; baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var implementationMethod = baseType.FindImplementationForInterfaceMember(constructedMethod); if (implementationMethod is null) { // we know no base type will implement this interface member either return false; } if (implementationMethod.ContainingType.IsInterface) { // this method cannot be called directly from source because an interface can only explicitly implement a method from its base interface. return false; } // could be calling an override of a method that implements the interface method for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.Equals(implementationMethod)) { return true; } } // the Equals method being called isn't the method that implements the interface method in this type. // it could be a method that implements the interface on a base type, so check again with the base type of 'implementationMethod.ContainingType' // e.g. in this hierarchy: // class A -> B -> C -> D // method virtual B.Equals -> override D.Equals // // we would potentially check: // 1. D.Equals when called on D, then B.Equals when called on D // 2. B.Equals when called on C // 3. B.Equals when called on B // 4. give up when checking A, since B.Equals is not overriding anything in A // we know that implementationMethod.ContainingType is the same type or a base type of 'baseType', // and that the implementation method will be the same between 'baseType' and 'implementationMethod.ContainingType'. // we step through the intermediate bases in order to skip unnecessary override methods. while (!baseType.Equals(implementationMethod.ContainingType) && method is object) { if (baseType.Equals(method.ContainingType)) { // since we're about to move on to the base of 'method.ContainingType', // we know the implementation could only be an overridden method of 'method'. method = method.OverriddenMethod; } baseType = baseType.BaseTypeNoUseSiteDiagnostics; // the implementation method must be contained in this 'baseType' or one of its bases. Debug.Assert(baseType is object); } // now 'baseType == implementationMethod.ContainingType', so if 'method' is // contained in that same type we should advance 'method' one more time. if (method is object && baseType.Equals(method.ContainingType)) { method = method.OverriddenMethod; } } return false; } void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) { // comparing anything to a null literal gives maybe-null when true and not-null when false // comparing a maybe-null to a not-null gives us not-null when true, nothing learned when false if (left.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(right, ref StateWhenTrue); LearnFromNonNullTest(right, ref StateWhenFalse); } else if (right.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(left, ref StateWhenTrue); LearnFromNonNullTest(left, ref StateWhenFalse); } else if (leftType.MayBeNull && rightType.IsNotNull) { Split(); LearnFromNonNullTest(left, ref StateWhenTrue); } else if (rightType.MayBeNull && leftType.IsNotNull) { Split(); LearnFromNonNullTest(right, ref StateWhenTrue); } } } private bool IsCompareExchangeMethod(MethodSymbol? method) { if (method is null) { return false; } return method.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange), SymbolEqualityComparer.ConsiderEverything.CompareKind) || method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T), SymbolEqualityComparer.ConsiderEverything.CompareKind); } private readonly struct CompareExchangeInfo { public readonly ImmutableArray<BoundExpression> Arguments; public readonly ImmutableArray<VisitArgumentResult> Results; public readonly ImmutableArray<int> ArgsToParamsOpt; public CompareExchangeInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> results, ImmutableArray<int> argsToParamsOpt) { Arguments = arguments; Results = results; ArgsToParamsOpt = argsToParamsOpt; } public bool IsDefault => Arguments.IsDefault || Results.IsDefault; } private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) { Debug.Assert(!compareExchangeInfo.IsDefault); // In general a call to CompareExchange of the form: // // Interlocked.CompareExchange(ref location, value, comparand); // // will be analyzed similarly to the following: // // if (location == comparand) // { // location = value; // } if (compareExchangeInfo.Arguments.Length != 3) { // This can occur if CompareExchange has optional arguments. // Since none of the main runtimes have optional arguments, // we bail to avoid an exception but don't bother actually calculating the FlowState. return NullableFlowState.NotNull; } var argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; Debug.Assert(argsToParamsOpt is { IsDefault: true } or { Length: 3 }); var (comparandIndex, valueIndex, locationIndex) = argsToParamsOpt.IsDefault ? (2, 1, 0) : (argsToParamsOpt.IndexOf(2), argsToParamsOpt.IndexOf(1), argsToParamsOpt.IndexOf(0)); var comparand = compareExchangeInfo.Arguments[comparandIndex]; var valueFlowState = compareExchangeInfo.Results[valueIndex].RValueType.State; if (comparand.ConstantValue?.IsNull == true) { // If location contained a null, then the write `location = value` definitely occurred } else { var locationFlowState = compareExchangeInfo.Results[locationIndex].RValueType.State; // A write may have occurred valueFlowState = valueFlowState.Join(locationFlowState); } return valueFlowState; } private TypeWithState VisitCallReceiver(BoundCall node) { var receiverOpt = node.ReceiverOpt; TypeWithState receiverType = default; if (receiverOpt != null) { receiverType = VisitRvalueWithState(receiverOpt); // methods which are members of Nullable<T> (ex: ToString, GetHashCode) can be invoked on null receiver. // However, inherited methods (ex: GetType) are invoked on a boxed value (since base types are reference types) // and therefore in those cases nullable receivers should be checked for nullness. bool checkNullableValueType = false; var type = receiverType.Type; var method = node.Method; if (method.RequiresInstanceReceiver && type?.IsNullableType() == true && method.ContainingType.IsReferenceType) { checkNullableValueType = true; } else if (method.OriginalDefinition == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { // call to get_Value may not occur directly in source, but may be inserted as a result of premature lowering. // One example where we do it is foreach with nullables. // The reason is Dev10 compatibility (see: UnwrapCollectionExpressionIfNullable in ForEachLoopBinder.cs) // Regardless of the reasons, we know that the method does not tolerate nulls. checkNullableValueType = true; } // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType); } return receiverType; } private TypeWithState GetReturnTypeWithState(MethodSymbol method) { return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); } private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = symbol.GetFlowAnalysisAnnotations(); return annotations & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); } private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) return IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : parameter.FlowAnalysisAnnotations; } /// <summary> /// Fix a TypeWithAnnotations based on Allow/DisallowNull annotations prior to a conversion or assignment. /// Note this does not work for nullable value types, so an additional check with <see cref="CheckDisallowedNullAssignment"/> may be required. /// </summary> private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) { if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) { return declaredType.AsNotAnnotated(); } else if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) { return declaredType.AsAnnotated(); } return declaredType; } /// <summary> /// Update the null-state based on MaybeNull/NotNull /// </summary> private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } return typeWithState; } private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return declaredType.AsAnnotated(); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return declaredType.AsNotAnnotated(); } return declaredType; } // https://github.com/dotnet/roslyn/issues/29863 Record in the node whether type // arguments were implicit, to allow for cases where the syntax is not an // invocation (such as a synthesized call from a query interpretation). private static bool HasImplicitTypeArguments(BoundNode node) { if (node is BoundCollectionElementInitializer { AddMethod: { TypeArgumentsWithAnnotations: { IsEmpty: false } } }) { return true; } if (node is BoundForEachStatement { EnumeratorInfoOpt: { GetEnumeratorInfo: { Method: { TypeArgumentsWithAnnotations: { IsEmpty: false } } } } }) { return true; } var syntax = node.Syntax; if (syntax.Kind() != SyntaxKind.InvocationExpression) { // Unexpected syntax kind. return false; } return HasImplicitTypeArguments(((InvocationExpressionSyntax)syntax).Expression); } private static bool HasImplicitTypeArguments(SyntaxNode syntax) { var nameSyntax = Binder.GetNameSyntax(syntax, out _); if (nameSyntax == null) { // Unexpected syntax kind. return false; } nameSyntax = nameSyntax.GetUnqualifiedName(); return nameSyntax.Kind() != SyntaxKind.GenericName; } protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { // Callers should be using VisitArguments overload below. throw ExceptionUtilities.Unreachable; } private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol? method, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray<VisitArgumentResult> VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, PropertySymbol? property, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// <summary> /// If you pass in a method symbol, its type arguments will be re-inferred and the re-inferred method will be returned. /// </summary> private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) { Debug.Assert(!arguments.IsDefault); bool shouldReturnNotNull = false; (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // Re-infer method type parameters if (method?.IsGenericMethod == true) { if (HasImplicitTypeArguments(node)) { method = InferMethodTypeArguments(method, GetArgumentsForMethodTypeInference(results, argumentsNoConversions), refKindsOpt, argsToParamsOpt, expanded); parametersOpt = method.Parameters; } if (ConstraintsHelper.RequiresChecking(method)) { var syntax = node.Syntax; CheckMethodConstraints( syntax switch { InvocationExpressionSyntax { Expression: var expression } => expression, ForEachStatementSyntax { Expression: var expression } => expression, _ => syntax }, method); } } bool parameterHasNotNullIfNotNull = !IsAnalyzingAttribute && !parametersOpt.IsDefault && parametersOpt.Any(p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; if (!parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentNoConversion; if (argument is not BoundConversion && argumentNoConversion is BoundLambda lambda) { Debug.Assert(node.HasErrors); Debug.Assert((object)argument == argumentNoConversion); // 'VisitConversion' only visits a lambda when the lambda has an AnonymousFunction conversion. // This lambda doesn't have a conversion, so we need to visit it here. VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); continue; } (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { // If this assert fails, we are missing necessary info to visit the // conversion of a target typed conditional or switch. Debug.Assert(argumentNoConversion is not (BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) && _conditionalInfoForConversionOpt?.ContainsKey(argumentNoConversion) is null or false); // If this assert fails, it means we failed to visit a lambda for error recovery above. Debug.Assert(argumentNoConversion is not BoundLambda); continue; } // We disable diagnostics when: // 1. the containing call has errors (to reduce cascading diagnostics) // 2. on implicit default arguments (since that's really only an issue with the declaration) var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= node.HasErrors || defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } if (node is BoundCall { Method: { OriginalDefinition: LocalFunctionSymbol localFunction } }) { VisitLocalFunctionUse(localFunction); } if (!node.HasErrors && !parametersOpt.IsDefault) { // For CompareExchange method we need more context to determine the state of outbound assignment CompareExchangeInfo compareExchangeInfo = IsCompareExchangeMethod(method) ? new CompareExchangeInfo(arguments, results, argsToParamsOpt) : default; // Visit outbound assignments and post-conditions // Note: the state may get split in this step for (int i = 0; i < arguments.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } VisitArgumentOutboundAssignmentsAndPostConditions( arguments[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], notNullParametersBuilder, (!compareExchangeInfo.IsDefault && parameter.Ordinal == 0) ? compareExchangeInfo : default); } } else { for (int i = 0; i < arguments.Length; i++) { // We can hit this case when dynamic methods are involved, or when there are errors. In either case we have no information, // so just assume that the conversions have the same nullability as the underlying result var argument = arguments[i]; var result = results[i]; var argumentNoConversion = argumentsNoConversions[i]; TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(argument.Type, result.RValueType.State), argument as BoundConversion, argumentNoConversion); } } if (!IsAnalyzingAttribute && method is object && (method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) { SetUnreachable(); } notNullParametersBuilder?.Free(); return (method, results, shouldReturnNotNull); } private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) { if (method is null) { return; } int receiverSlot = method.IsStatic ? 0 : receiverOpt is null ? -1 : MakeSlot(receiverOpt); if (receiverSlot < 0) { return; } ApplyMemberPostConditions(receiverSlot, method); } private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) { Debug.Assert(receiverSlot >= 0); do { var type = method.ContainingType; var notNullMembers = method.NotNullMembers; var notNullWhenTrueMembers = method.NotNullWhenTrueMembers; var notNullWhenFalseMembers = method.NotNullWhenFalseMembers; if (IsConditionalState) { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenFalse); } else { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref State); } if (!notNullWhenTrueMembers.IsEmpty || !notNullWhenFalseMembers.IsEmpty) { Split(); applyMemberPostConditions(receiverSlot, type, notNullWhenTrueMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullWhenFalseMembers, ref StateWhenFalse); } method = method.OverriddenMethod; } while (method != null); void applyMemberPostConditions(int receiverSlot, TypeSymbol type, ImmutableArray<string> members, ref LocalState state) { if (members.IsEmpty) { return; } foreach (var memberName in members) { markMembersAsNotNull(receiverSlot, type, memberName, ref state); } } void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, ref LocalState state) { foreach (Symbol member in type.GetMembers(memberName)) { if (member.IsStatic) { receiverSlot = 0; } switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (GetOrCreateSlot(member, receiverSlot) is int memberSlot && memberSlot > 0) { state[memberSlot] = NullableFlowState.NotNull; } break; case SymbolKind.Event: case SymbolKind.Method: break; } } } } private ImmutableArray<VisitArgumentResult> VisitArgumentsEvaluate( SyntaxNode syntax, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var visitedParameters = PooledHashSet<ParameterSymbol?>.GetInstance(); var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); return resultsBuilder.ToImmutableAndFree(); } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) { Debug.Assert(!IsConditionalState); var savedState = (argument.Kind == BoundKind.Lambda) ? this.State.Clone() : default(Optional<LocalState>); // Note: DoesNotReturnIf is ineffective on ref/out parameters switch (refKind) { case RefKind.Ref: Visit(argument); Unsplit(); break; case RefKind.None: case RefKind.In: switch (annotations & (FlowAnalysisAnnotations.DoesNotReturnIfTrue | FlowAnalysisAnnotations.DoesNotReturnIfFalse)) { case FlowAnalysisAnnotations.DoesNotReturnIfTrue: Visit(argument); if (IsConditionalState) { SetState(StateWhenFalse); } break; case FlowAnalysisAnnotations.DoesNotReturnIfFalse: Visit(argument); if (IsConditionalState) { SetState(StateWhenTrue); } break; default: VisitRvalue(argument); break; } break; case RefKind.Out: // As far as we can tell, there is no scenario relevant to nullability analysis // where splitting an L-value (for instance with a ref conditional) would affect the result. Visit(argument); // We'll want to use the l-value type, rather than the result type, for method re-inference UseLvalueOnly(argument); break; } Debug.Assert(!IsConditionalState); return new VisitArgumentResult(_visitResult, savedState); } /// <summary> /// Verifies that an argument's nullability is compatible with its parameter's on the way in. /// </summary> private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, bool extensionMethodThisArgument) { Debug.Assert(!this.IsConditionalState); // Note: we allow for some variance in `in` and `out` cases. Unlike in binding, we're not // limited by CLR constraints. var resultType = result.RValueType; switch (refKind) { case RefKind.None: case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) { var argumentResultType = resultType.Type; conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false); if (!conversion.Exists && !argumentNoConversion.IsSuppressed) { Debug.Assert(argumentResultType is not null); ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); } } var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, conversion: conversion, targetTypeWithNullability: ApplyLValueAnnotations(parameterType, parameterAnnotations), operandType: resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter, extensionMethodThisArgument: extensionMethodThisArgument, stateForLambda: result.StateForLambda); // If the parameter has annotations, we perform an additional check for nullable value types if (CheckDisallowedNullAssignment(stateAfterConversion, parameterAnnotations, argumentNoConversion.Syntax.Location)) { LearnFromNonNullTest(argumentNoConversion, ref State); } SetResultType(argumentNoConversion, stateAfterConversion, updateAnalyzedNullability: false); } break; case RefKind.Ref: if (!argumentNoConversion.IsSuppressed) { var lvalueResultType = result.LValueType; if (IsNullabilityMismatch(lvalueResultType.Type, parameterType.Type)) { // declared types must match, ignoring top-level nullability ReportNullabilityMismatchInRefArgument(argumentNoConversion, argumentType: lvalueResultType.Type, parameter, parameterType.Type); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), resultType, useLegacyWarnings: false); // If the parameter has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, argumentNoConversion.Syntax.Location); } } break; case RefKind.Out: break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } Debug.Assert(!this.IsConditionalState); } /// <summary>Returns <see langword="true"/> if this is an assignment forbidden by DisallowNullAttribute, otherwise <see langword="false"/>.</summary> private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, Location location, BoundExpression? boundValueOpt = null) { if (boundValueOpt is { WasCompilerGenerated: true }) { // We need to skip `return backingField;` in auto-prop getters return false; } // We do this extra check for types whose non-nullable version cannot be represented if (IsDisallowedNullAssignment(state, annotations)) { ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, location); return true; } return false; } private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) { return ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) && hasNoNonNullableCounterpart(valueState.Type) && valueState.MayBeNull; static bool hasNoNonNullableCounterpart(TypeSymbol? type) { if (type is null) { return false; } // Some types that could receive a maybe-null value have a NotNull counterpart: // [NotNull]string? -> string // [NotNull]string -> string // [NotNull]TClass -> TClass // [NotNull]TClass? -> TClass // // While others don't: // [NotNull]int? -> X // [NotNull]TNullable -> X // [NotNull]TStruct? -> X // [NotNull]TOpen -> X return (type.Kind == SymbolKind.TypeParameter && !type.IsReferenceType) || type.IsNullableTypeOrTypeParameter(); } } /// <summary> /// Verifies that outbound assignments (from parameter to argument) are safe and /// tracks those assignments (or learns from post-condition attributes) /// </summary> private void VisitArgumentOutboundAssignmentsAndPostConditions( BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) { // Note: the state may be conditional if a previous argument involved a conditional post-condition // The WhenTrue/False states correspond to the invocation returning true/false switch (refKind) { case RefKind.None: case RefKind.In: { // learn from post-conditions [Maybe/NotNull, Maybe/NotNullWhen] without using an assignment learnFromPostConditions(argument, parameterType, parameterAnnotations); } break; case RefKind.Ref: { // assign from a fictional value from the parameter to the argument. parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); if (!compareExchangeInfoOpt.IsDefault) { var adjustedState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); parameterWithState = TypeWithState.Create(parameterType.Type, adjustedState); } var parameterValue = new BoundParameter(argument.Syntax, parameter); var lValueType = result.LValueType; trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // check whether parameter would unsafely let a null out in the worse case if (!argument.IsSuppressed) { var leftAnnotations = GetLValueAnnotations(argument); ReportNullableAssignmentIfNecessary( parameterValue, targetType: ApplyLValueAnnotations(lValueType, leftAnnotations), valueType: applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations), UseLegacyWarnings(argument, result.LValueType)); } } break; case RefKind.Out: { // compute the fictional parameter state parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); // Adjust parameter state if MaybeNull or MaybeNullWhen are present (for `var` type and for assignment warnings) var worstCaseParameterWithState = applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations); var declaredType = result.LValueType; var leftAnnotations = GetLValueAnnotations(argument); var lValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType) { var varType = worstCaseParameterWithState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local.LocalSymbol, varType); lValueType = varType; } else if (argument is BoundDiscardExpression discard) { SetAnalyzedNullability(discard, new VisitResult(parameterWithState, parameterWithState.ToTypeWithAnnotations(compilation)), isLvalue: true); } // track state by assigning from a fictional value from the parameter to the argument. var parameterValue = new BoundParameter(argument.Syntax, parameter); // If the argument type has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(parameterWithState, leftAnnotations, argument.Syntax.Location); AdjustSetValue(argument, ref parameterWithState); trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // report warnings if parameter would unsafely let a null out in the worst case if (!argument.IsSuppressed) { ReportNullableAssignmentIfNecessary(parameterValue, lValueType, worstCaseParameterWithState, UseLegacyWarnings(argument, result.LValueType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, lValueType.Type, ref discardedUseSiteInfo)) { ReportNullabilityMismatchInArgument(argument.Syntax, lValueType.Type, parameter, parameterType.Type, forOutput: true); } } } break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations parameterAnnotations, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, ParameterSymbol parameter) { if (!IsAnalyzingAttribute && notNullParametersOpt is object) { var notNullIfParameterNotNull = parameter.NotNullIfParameterNotNull; if (!notNullIfParameterNotNull.IsEmpty) { foreach (var notNullParameter in notNullParametersOpt) { if (notNullIfParameterNotNull.Contains(notNullParameter.Name)) { return FlowAnalysisAnnotations.NotNull; } } } } return parameterAnnotations; } void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations lValueType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations parameterAnnotations) { if (!IsConditionalState && !hasConditionalPostCondition(parameterAnnotations)) { TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); } else { Split(); var originalWhenFalse = StateWhenFalse.Clone(); SetState(StateWhenTrue); // Note: the suppression applies over the post-condition attributes TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); var newWhenTrue = State.Clone(); SetState(originalWhenFalse); TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); SetConditionalState(newWhenTrue, whenFalse: State); } } static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) { return (((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0)) || (((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0)); } static TypeWithState applyPostConditionsUnconditionally(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNull return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenTrue(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && !(maybeNullWhenFalse && notNullWhenTrue)) { // [MaybeNull, NotNullWhen(true)] means [MaybeNullWhen(false)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenTrue) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenFalse(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenFalse && !(maybeNullWhenTrue && notNullWhenFalse)) { // [MaybeNull, NotNullWhen(false)] means [MaybeNullWhen(true)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenFalse) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } void learnFromPostConditions(BoundExpression argument, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { // Note: NotNull = NotNullWhen(true) + NotNullWhen(false) bool notNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool notNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; // Note: MaybeNull = MaybeNullWhen(true) + MaybeNullWhen(false) bool maybeNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && maybeNullWhenFalse && !IsConditionalState && !(notNullWhenTrue && notNullWhenFalse)) { LearnFromNullTest(argument, ref State); } else if (notNullWhenTrue && notNullWhenFalse && !IsConditionalState && !(maybeNullWhenTrue || maybeNullWhenFalse)) { LearnFromNonNullTest(argument, ref State); } else if (notNullWhenTrue || notNullWhenFalse || maybeNullWhenTrue || maybeNullWhenFalse) { Split(); if (notNullWhenTrue) { LearnFromNonNullTest(argument, ref StateWhenTrue); } if (notNullWhenFalse) { LearnFromNonNullTest(argument, ref StateWhenFalse); } if (maybeNullWhenTrue) { LearnFromNullTest(argument, ref StateWhenTrue); } if (maybeNullWhenFalse) { LearnFromNullTest(argument, ref StateWhenFalse); } } } } private (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) RemoveArgumentConversions( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { int n = arguments.Length; var conversions = default(ImmutableArray<Conversion>); if (n > 0) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n); bool includedConversion = false; for (int i = 0; i < n; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); var argument = arguments[i]; var conversion = Conversion.Identity; if (refKind == RefKind.None) { var before = argument; (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false); if (argument != before) { SnapshotWalkerThroughConversionGroup(before, argument); includedConversion = true; } } argumentsBuilder.Add(argument); conversionsBuilder.Add(conversion); } if (includedConversion) { arguments = argumentsBuilder.ToImmutable(); conversions = conversionsBuilder.ToImmutable(); } argumentsBuilder.Free(); conversionsBuilder.Free(); } return (arguments, conversions); } private static VariableState GetVariableState(Variables variables, LocalState localState) { Debug.Assert(variables.Id == localState.Id); return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); } private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { if (parametersOpt.IsDefault) { return default; } var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); return default; } var type = parameter.TypeWithAnnotations; if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); } return (parameter, type, GetParameterAnnotations(parameter), isExpandedParamsArgument: false); } private MethodSymbol InferMethodTypeArguments( MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { Debug.Assert(method.IsGenericMethod); // https://github.com/dotnet/roslyn/issues/27961 OverloadResolution.IsMemberApplicableInNormalForm and // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here. var definition = method.ConstructedFrom; var refKinds = ArrayBuilder<RefKind>.GetInstance(); if (argumentRefKindsOpt != null) { refKinds.AddRange(argumentRefKindsOpt); } // https://github.com/dotnet/roslyn/issues/27961 Do we really need OverloadResolution.GetEffectiveParameterTypes? // Aren't we doing roughly the same calculations in GetCorrespondingParameter? OverloadResolution.GetEffectiveParameterTypes( definition, arguments.Length, argsToParamsOpt, refKinds, isMethodGroupConversion: false, // https://github.com/dotnet/roslyn/issues/27961 `allowRefOmittedArguments` should be // false for constructors and several other cases (see Binder use). Should we // capture the original value in the BoundCall? allowRefOmittedArguments: true, binder: _binder, expanded: expanded, parameterTypes: out ImmutableArray<TypeWithAnnotations> parameterTypes, parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds); refKinds.Free(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var result = MethodTypeInferrer.Infer( _binder, _conversions, definition.TypeParameters, definition.ContainingType, parameterTypes, parameterRefKinds, arguments, ref discardedUseSiteInfo, new MethodInferenceExtensions(this)); if (!result.Success) { return method; } return definition.Construct(result.InferredTypeArguments); } private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions { private readonly NullableWalker _walker; internal MethodInferenceExtensions(NullableWalker walker) { _walker = walker; } internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); } /// <summary> /// Return top-level nullability for the expression. This method should be called on a limited /// set of expressions only. It should not be called on expressions tracked by flow analysis /// other than <see cref="BoundKind.ExpressionWithNullability"/> which is an expression /// specifically created in NullableWalker to represent the flow analysis state. /// </summary> private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) { switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Literal: return expr.ConstantValue == ConstantValue.NotAvailable || !expr.ConstantValue.IsNull || expr.IsSuppressed ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: return NullableAnnotation.NotAnnotated; default: Debug.Assert(false); // unexpected value return NullableAnnotation.Oblivious; } } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out TypeWithState receiverType)) { if (!method.IsStatic) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } } return method.ReturnTypeWithAnnotations; } } private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<BoundExpression> arguments) { // https://github.com/dotnet/roslyn/issues/27961 MethodTypeInferrer.Infer relies // on the BoundExpressions for tuple element types and method groups. // By using a generic BoundValuePlaceholder, we're losing inference in those cases. // https://github.com/dotnet/roslyn/issues/27961 Inference should be based on // unconverted arguments. Consider cases such as `default`, lambdas, tuples. int n = argumentResults.Length; var builder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var visitArgumentResult = argumentResults[i]; var lambdaState = visitArgumentResult.StateForLambda; // Note: for `out` arguments, the argument result contains the declaration type (see `VisitArgumentEvaluate`) var argumentResult = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResult, lambdaState)); } return builder.ToImmutableAndFree(); BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations argumentType, Optional<LocalState> lambdaState) { if (argument.Kind == BoundKind.Lambda) { Debug.Assert(lambdaState.HasValue); // MethodTypeInferrer must infer nullability for lambdas based on the nullability // from flow analysis rather than the declared nullability. To allow that, we need // to re-bind lambdas in MethodTypeInferrer. return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); } if (!argumentType.HasType) { return argument; } if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } or BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) { // target-typed contexts don't contribute to nullability return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, type: null); } return new BoundExpressionWithNullability(argument.Syntax, argument, argumentType.NullableAnnotation, argumentType.Type); } static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) { return expr.UnboundLambda.WithNullableState(variableState); } } private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) { if (_disableDiagnostics) { return; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var nullabilityBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), diagnosticsBuilder, nullabilityBuilder, ref useSiteDiagnosticsBuilder); foreach (var pair in nullabilityBuilder) { if (pair.UseSiteInfo.DiagnosticInfo is object) { Diagnostics.Add(pair.UseSiteInfo.DiagnosticInfo, syntax.Location); } } useSiteDiagnosticsBuilder?.Free(); nullabilityBuilder.Free(); diagnosticsBuilder.Free(); } /// <summary> /// Returns the expression without the top-most conversion plus the conversion. /// If the expression is not a conversion, returns the original expression plus /// the Identity conversion. If `includeExplicitConversions` is true, implicit and /// explicit conversions are considered. If `includeExplicitConversions` is false /// only implicit conversions are considered and if the expression is an explicit /// conversion, the expression is returned as is, with the Identity conversion. /// (Currently, the only visit method that passes `includeExplicitConversions: true` /// is VisitConversion. All other callers are handling implicit conversions only.) /// </summary> private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) { ConversionGroup? group = null; while (true) { if (expr.Kind != BoundKind.Conversion) { break; } var conversion = (BoundConversion)expr; if (group != conversion.ConversionGroupOpt && group != null) { // E.g.: (C)(B)a break; } group = conversion.ConversionGroupOpt; Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group. if (!includeExplicitConversions && group?.IsExplicitConversion == true) { return (expr, Conversion.Identity); } expr = conversion.Operand; if (group == null) { // Ungrouped conversion should not be followed by another ungrouped // conversion. Otherwise, the conversions should have been grouped. // https://github.com/dotnet/roslyn/issues/34919 This assertion does not always hold true for // enum initializers //Debug.Assert(expr.Kind != BoundKind.Conversion || // ((BoundConversion)expr).ConversionGroupOpt != null || // ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion); return (expr, conversion.Conversion); } } return (expr, group?.Conversion ?? Conversion.Identity); } // See Binder.BindNullCoalescingOperator for initial binding. private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false); bool canConvertNestedNullability = conversion.Exists; if (!canConvertNestedNullability && reportMismatch && !sourceExpression.IsSuppressed) { ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); } return conversion; } private static Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool useExpression = sourceType is null || UseExpressionForConversion(sourceExpression); if (extensionMethodThisArgument) { return conversions.ClassifyImplicitExtensionMethodThisArgConversion( useExpression ? sourceExpression : null, sourceType, destinationType, ref discardedUseSiteInfo); } return useExpression ? (fromExplicitCast ? conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo)); } /// <summary> /// Returns true if the expression should be used as the source when calculating /// a conversion from this expression, rather than using the type (with nullability) /// calculated by visiting this expression. Typically, that means expressions that /// do not have an explicit type but there are several other cases as well. /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.) /// </summary> private static bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) { if (value is null) { return false; } if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null) { return true; } switch (value.Kind) { case BoundKind.InterpolatedString: return true; default: return false; } } /// <summary> /// Adjust declared type based on inferred nullability at the point of reference. /// </summary> private TypeWithState GetAdjustedResult(TypeWithState type, int slot) { if (this.State.HasValue(slot)) { NullableFlowState state = this.State[slot]; return TypeWithState.Create(type.Type, state); } return type; } /// <summary> /// Gets the corresponding member for a symbol from initial binding to match an updated receiver type in NullableWalker. /// For instance, this will map from List&lt;string~&gt;.Add(string~) to List&lt;string?&gt;.Add(string?) in the following example: /// <example> /// string s = null; /// var list = new[] { s }.ToList(); /// list.Add(null); /// </example> /// </summary> private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) { Debug.Assert((object)symbol != null); var containingType = type as NamedTypeSymbol; if (containingType is null || containingType.IsErrorType() || symbol is ErrorMethodSymbol) { return symbol; } if (symbol.Kind == SymbolKind.Method) { if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { // https://github.com/dotnet/roslyn/issues/27233 Handle type substitution for local functions. return symbol; } } if (symbol is TupleElementFieldSymbol or TupleErrorFieldSymbol) { return symbol.SymbolAsMember(containingType); } var symbolContainer = symbol.ContainingType; if (symbolContainer.IsAnonymousType) { int? memberIndex = symbol.Kind == SymbolKind.Property ? symbol.MemberIndexOpt : null; if (!memberIndex.HasValue) { return symbol; } return AnonymousTypeManager.GetAnonymousTypeProperty(containingType, memberIndex.GetValueOrDefault()); } if (!symbolContainer.IsGenericType) { Debug.Assert(symbol.ContainingType.IsDefinition); return symbol; } if (!containingType.IsGenericType) { return symbol; } if (symbolContainer.IsInterface) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } foreach (var @interface in containingType.AllInterfacesNoUseSiteDiagnostics) { if (tryAsMemberOfSingleType(@interface, out result)) { return result; } } } else { while (true) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } containingType = containingType.BaseTypeNoUseSiteDiagnostics; if ((object)containingType == null) { break; } } } Debug.Assert(false); // If this assert fails, add an appropriate test. return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) { if (!singleType.Equals(symbolContainer, TypeCompareKind.AllIgnoreOptions)) { result = null; return false; } var symbolDef = symbol.OriginalDefinition; result = symbolDef.SymbolAsMember(singleType); if (result is MethodSymbol resultMethod && resultMethod.IsGenericMethod) { result = resultMethod.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); } return true; } } public override BoundNode? VisitConversion(BoundConversion node) { // https://github.com/dotnet/roslyn/issues/35732: Assert VisitConversion is only used for explicit conversions. //Debug.Assert(node.ExplicitCastInCode); //Debug.Assert(node.ConversionGroupOpt != null); //Debug.Assert(node.ConversionGroupOpt.ExplicitType.HasType); TypeWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(node.Type); Debug.Assert(targetType.HasType); (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true); SnapshotWalkerThroughConversionGroup(node, operand); TypeWithState operandType = VisitRvalueWithState(operand); SetResultType(node, VisitConversion( node, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: fromExplicitCast, useLegacyWarnings: fromExplicitCast, AssignmentKind.Assignment, reportTopLevelWarnings: fromExplicitCast, reportRemainingWarnings: true, trackMembers: true)); return null; } /// <summary> /// Visit an expression. If an explicit target type is provided, the expression is converted /// to that type. This method should be called whenever an expression may contain /// an implicit conversion, even if that conversion was omitted from the bound tree, /// so the conversion can be re-classified with nullability. /// </summary> private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) { if (!targetTypeOpt.HasType) { return VisitRvalueWithState(expr); } (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); // If an explicit conversion was used in place of an implicit conversion, the explicit // conversion was created by initial binding after reporting "error CS0266: // Cannot implicitly convert type '...' to '...'. An explicit conversion exists ...". // Since an error was reported, we don't need to report nested warnings as well. bool reportNestedWarnings = !conversion.IsExplicit; var resultType = VisitConversion( GetConversionIfApplicable(expr, operand), operand, conversion, targetTypeOpt, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: useLegacyWarnings, assignmentKind, reportTopLevelWarnings: true, reportRemainingWarnings: reportNestedWarnings, trackMembers: trackMembers); return resultType; } private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) { if (nullableTypeOpt?.IsNullableType() == true && underlyingTypeOpt?.IsNullableType() == false) { var typeArg = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); if (typeArg.Type.Equals(underlyingTypeOpt, TypeCompareKind.AllIgnoreOptions)) { underlyingTypeWithAnnotations = typeArg; return true; } } underlyingTypeWithAnnotations = default; return false; } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { VisitTupleExpression(node); return null; } public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { Debug.Assert(!IsConditionalState); var savedState = this.State.Clone(); // Visit the source tuple so that the semantic model can correctly report nullability for it // Disable diagnostics, as we don't want to duplicate any that are produced by visiting the converted literal below VisitWithoutDiagnostics(node.SourceTuple); this.SetState(savedState); VisitTupleExpression(node); return null; } private void VisitTupleExpression(BoundTupleExpression node) { var arguments = node.Arguments; ImmutableArray<TypeWithState> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithState(a), this); ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations = elementTypes.SelectAsArray(a => a.ToTypeWithAnnotations(compilation)); var tupleOpt = (NamedTypeSymbol?)node.Type; if (tupleOpt is null) { SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); } else { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; TrackNullableStateOfTupleElements(slot, tupleOpt, arguments, elementTypes, argsToParamsOpt: default, useRestField: false); } tupleOpt = tupleOpt.WithElementTypes(elementTypesWithAnnotations); if (!_disableDiagnostics) { var locations = tupleOpt.TupleElements.SelectAsArray((element, location) => element.Locations.FirstOrDefault() ?? location, node.Syntax.Location); tupleOpt.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, diagnostics: null), typeSyntax: node.Syntax, locations, nullabilityDiagnosticsOpt: new BindingDiagnosticBag(Diagnostics)); } SetResultType(node, TypeWithState.Create(tupleOpt, NullableFlowState.NotNull)); } } /// <summary> /// Set the nullability of tuple elements for tuples at the point of construction. /// If <paramref name="useRestField"/> is true, the tuple was constructed with an explicit /// 'new ValueTuple' call, in which case the 8-th element, if any, represents the 'Rest' field. /// </summary> private void TrackNullableStateOfTupleElements( int slot, NamedTypeSymbol tupleType, ImmutableArray<BoundExpression> values, ImmutableArray<TypeWithState> types, ImmutableArray<int> argsToParamsOpt, bool useRestField) { Debug.Assert(tupleType.IsTupleType); Debug.Assert(values.Length == types.Length); Debug.Assert(values.Length == (useRestField ? Math.Min(tupleType.TupleElements.Length, NamedTypeSymbol.ValueTupleRestPosition) : tupleType.TupleElements.Length)); if (slot > 0) { var tupleElements = tupleType.TupleElements; int n = values.Length; if (useRestField) { n = Math.Min(n, NamedTypeSymbol.ValueTupleRestPosition - 1); } for (int i = 0; i < n; i++) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(i); trackState(values[argOrdinal], tupleElements[i], types[argOrdinal]); } if (useRestField && values.Length == NamedTypeSymbol.ValueTupleRestPosition && tupleType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() is FieldSymbol restField) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(NamedTypeSymbol.ValueTupleRestPosition - 1); trackState(values[argOrdinal], restField, types[argOrdinal]); } } void trackState(BoundExpression value, FieldSymbol field, TypeWithState valueType) { int targetSlot = GetOrCreateSlot(field, slot); TrackNullableStateForAssignment(value, field.TypeWithAnnotations, targetSlot, valueType, MakeSlot(value)); } int GetArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) { var index = argsToParamsOpt.IsDefault ? parameterOrdinal : argsToParamsOpt.IndexOf(parameterOrdinal); Debug.Assert(index != -1); return index; } } private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) { Debug.Assert(containingType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T); Debug.Assert(containingSlot > 0); Debug.Assert(valueSlot > 0); int targetSlot = GetNullableOfTValueSlot(containingType, containingSlot, out Symbol? symbol); if (targetSlot > 0) { TrackNullableStateForAssignment(value, symbol!.GetTypeOrReturnType(), targetSlot, valueType, valueSlot); } } private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) { Debug.Assert(conversion.Kind == ConversionKind.ImplicitTuple || conversion.Kind == ConversionKind.ExplicitTuple); Debug.Assert(slot > 0); Debug.Assert(valueSlot > 0); var valueTuple = operandType as NamedTypeSymbol; if (valueTuple is null || !valueTuple.IsTupleType) { return; } var conversions = conversion.UnderlyingConversions; var targetElements = ((NamedTypeSymbol)targetType).TupleElements; var valueElements = valueTuple.TupleElements; int n = valueElements.Length; for (int i = 0; i < n; i++) { trackConvertedValue(targetElements[i], conversions[i], valueElements[i]); } void trackConvertedValue(FieldSymbol targetField, Conversion conversion, FieldSymbol valueField) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: case ConversionKind.Boxing: case ConversionKind.Unboxing: InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, skipSlot: slot); break; case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion, targetField.Type, valueField.Type, targetFieldSlot, valueFieldSlot, assignmentKind, parameterOpt, reportWarnings); } } } break; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out _)) { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfNullableValue(targetFieldSlot, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), valueFieldSlot); } } } break; case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: { var convertedType = VisitUserDefinedConversion( conversionOpt, convertedNode, conversion, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: reportWarnings, diagnosticLocation: (conversionOpt ?? convertedNode).Syntax.GetLocation()); int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = convertedType.State; } } break; default: break; } } } public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { base.VisitTupleBinaryOperator(node); SetNotNullResult(node); return null; } private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceInvokeMethod, new BindingDiagnosticBag(Diagnostics), reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: (targetType, location), invokedAsExtensionMethod: invokedAsExtensionMethod); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, new FormattedSymbol(sourceInvokeMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); } } private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, UnboundLambda unboundLambda) { if (!unboundLambda.HasExplicitlyTypedParameterList) { return; } var invoke = delegateType?.DelegateInvokeMethod; if (invoke is null) { return; } Debug.Assert(delegateType is object); if (unboundLambda.HasExplicitReturnType(out _, out var returnType) && IsNullabilityMismatch(invoke.ReturnTypeWithAnnotations, returnType, requireIdentity: true)) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount); for (int i = 0; i < count; i++) { var invokeParameter = invoke.Parameters[i]; // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding. // Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability. // (Compare with method group conversions which pass `requireIdentity: false`.) if (IsNullabilityMismatch(invokeParameter.TypeWithAnnotations, unboundLambda.ParameterTypeWithAnnotations(i), requireIdentity: true)) { // Should the warning be reported using location of specific lambda parameter? ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(i), unboundLambda.MessageID.Localize(), delegateType); } } } private bool IsNullabilityMismatch(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity)) { return true; } if (requireIdentity) { return IsNullabilityMismatch(source, destination); } var sourceType = source.Type; var destinationType = destination.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo).Exists; } private bool HasTopLevelNullabilityConversion(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { return requireIdentity ? _conversions.HasTopLevelNullabilityIdentityConversion(source, destination) : _conversions.HasTopLevelNullabilityImplicitConversion(source, destination); } /// <summary> /// Gets the conversion node for passing to <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional{LocalState}, bool, Location)"/>, /// if one should be passed. /// </summary> private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) { Debug.Assert(conversionOpt is null || convertedNode == conversionOpt // Note that convertedNode itself can be a BoundConversion, so we do this check explicitly // because the below calls to RemoveConversion could potentially strip that conversion. || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: false).expression || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: true).expression); return conversionOpt == convertedNode ? null : (BoundConversion?)conversionOpt; } /// <summary> /// Apply the conversion to the type of the operand and return the resulting type. /// If the operand does not have an explicit type, the operand expression is used. /// </summary> /// <param name="checkConversion"> /// If <see langword="true"/>, the incoming conversion is assumed to be from binding /// and will be re-calculated, this time considering nullability. /// Note that the conversion calculation considers nested nullability only. /// The caller is responsible for checking the top-level nullability of /// the type returned by this method. /// </param> /// <param name="trackMembers"> /// If <see langword="true"/>, the nullability of any members of the operand /// will be copied to the converted result when possible. /// </param> /// <param name="useLegacyWarnings"> /// If <see langword="true"/>, indicates that the "non-safety" diagnostic <see cref="ErrorCode.WRN_ConvertingNullableToNonNullable"/> /// should be given for an invalid conversion. /// </param> private TypeWithState VisitConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional<LocalState> stateForLambda = default, bool trackMembers = false, Location? diagnosticLocationOpt = null) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != null); NullableFlowState resultState = NullableFlowState.NotNull; bool canConvertNestedNullability = true; bool isSuppressed = false; diagnosticLocationOpt ??= (conversionOpt ?? conversionOperand).Syntax.GetLocation(); if (conversionOperand.IsSuppressed == true) { reportTopLevelWarnings = false; reportRemainingWarnings = false; isSuppressed = true; } #nullable disable TypeSymbol targetType = targetTypeWithNullability.Type; switch (conversion.Kind) { case ConversionKind.MethodGroup: { var group = conversionOperand as BoundMethodGroup; var (invokeSignature, parameters) = getDelegateOrFunctionPointerInfo(targetType); var method = conversion.Method; if (group != null) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } method = CheckMethodGroupReceiverNullability(group, parameters, method, conversion.IsExtensionMethod); } if (reportRemainingWarnings && invokeSignature != null) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, targetType, invokeSignature, method, conversion.IsExtensionMethod); } } resultState = NullableFlowState.NotNull; break; static (MethodSymbol invokeSignature, ImmutableArray<ParameterSymbol>) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) => targetType switch { NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { Parameters: { } parameters } signature } => (signature, parameters), FunctionPointerTypeSymbol { Signature: { Parameters: { } parameters } signature } => (signature, parameters), _ => (null, ImmutableArray<ParameterSymbol>.Empty), }; case ConversionKind.AnonymousFunction: if (conversionOperand is BoundLambda lambda) { var delegateType = targetType.GetDelegateType(); VisitLambda(lambda, delegateType, stateForLambda); if (reportRemainingWarnings) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, delegateType, lambda.UnboundLambda); } TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); return TypeWithState.Create(targetType, NullableFlowState.NotNull); } break; case ConversionKind.FunctionType: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedString: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedStringHandler: // https://github.com/dotnet/roslyn/issues/54583 Handle resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = visitNestedTargetTypedConstructs(); TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); break; case ConversionKind.ExplicitUserDefined: case ConversionKind.ImplicitUserDefined: return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt); case ConversionKind.ExplicitDynamic: case ConversionKind.ImplicitDynamic: resultState = getConversionResultState(operandType); break; case ConversionKind.Boxing: resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); break; case ConversionKind.Unboxing: if (targetType.IsNonNullableValueType()) { if (!operandType.IsNotNull && reportRemainingWarnings) { ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, diagnosticLocationOpt); } LearnFromNonNullTest(conversionOperand, ref State); } else { resultState = getUnboxingConversionResultState(operandType); } break; case ConversionKind.ImplicitThrow: resultState = NullableFlowState.NotNull; break; case ConversionKind.NoConversion: resultState = getConversionResultState(operandType); break; case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: checkConversion = false; goto case ConversionKind.Identity; case ConversionKind.Identity: // If the operand is an explicit conversion, and this identity conversion // is converting to the same type including nullability, skip the conversion // to avoid reporting redundant warnings. Also check useLegacyWarnings // since that value was used when reporting warnings for the explicit cast. // Don't skip the node when it's a user-defined conversion, as identity conversions // on top of user-defined conversions means that we're coming in from VisitUserDefinedConversion // and that any warnings caught by this recursive call of VisitConversion won't be redundant. if (useLegacyWarnings && conversionOperand is BoundConversion operandConversion && !operandConversion.ConversionKind.IsUserDefinedConversion()) { var explicitType = operandConversion.ConversionGroupOpt?.ExplicitType; if (explicitType?.Equals(targetTypeWithNullability, TypeCompareKind.ConsiderEverything) == true) { TrackAnalyzedNullabilityThroughConversionGroup( calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, targetType), conversionOpt, conversionOperand); return operandType; } } if (operandType.Type?.IsTupleType == true || conversionOperand.Kind == BoundKind.TupleLiteral) { goto case ConversionKind.ImplicitTuple; } goto case ConversionKind.ImplicitReference; case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: // Inherit state from the operand. if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State; break; case ConversionKind.ImplicitNullable: if (trackMembers) { Debug.Assert(conversionOperand != null); if (AreNullableAndUnderlyingTypes(targetType, operandType.Type, out TypeWithAnnotations underlyingType)) { // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int containingSlot = GetOrCreatePlaceholderSlot(conversionOpt); Debug.Assert(containingSlot > 0); TrackNullableStateOfNullableValue(containingSlot, targetType, conversionOperand, underlyingType.ToTypeWithState(), valueSlot); } } } if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = operandType.State; break; case ConversionKind.ExplicitNullable: if (operandType.Type?.IsNullableType() == true && !targetType.IsNullableType()) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. if (reportTopLevelWarnings && operandType.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, diagnosticLocationOpt); } // Mark the value as not nullable, regardless of whether it was known to be nullable, // because the implied call to `.Value` will only succeed if not null. if (conversionOperand != null) { LearnFromNonNullTest(conversionOperand, ref State); } } goto case ConversionKind.ImplicitNullable; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: if (trackMembers) { Debug.Assert(conversionOperand != null); switch (conversion.Kind) { case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int slot = GetOrCreatePlaceholderSlot(conversionOpt); if (slot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, targetType, operandType.Type, slot, valueSlot, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings); } } break; } } if (checkConversion && !targetType.IsErrorType()) { // https://github.com/dotnet/roslyn/issues/29699: Report warnings for user-defined conversions on tuple elements. conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = NullableFlowState.NotNull; break; case ConversionKind.Deconstruction: // Can reach here, with an error type, when the // Deconstruct method is missing or inaccessible. break; case ConversionKind.ExplicitEnumeration: // Can reach here, with an error type. break; default: Debug.Assert(targetType.IsValueType || targetType.IsErrorType()); break; } TypeWithState resultType = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, targetType); if (operandType.Type?.IsErrorType() != true && !targetType.IsErrorType()) { // Need to report all warnings that apply since the warnings can be suppressed individually. if (reportTopLevelWarnings) { ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, resultType, useLegacyWarnings, assignmentKind, parameterOpt, diagnosticLocationOpt); } if (reportRemainingWarnings && !canConvertNestedNullability) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocationOpt, operandType.Type, parameterOpt, targetType, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocationOpt, GetTypeAsDiagnosticArgument(operandType.Type), targetType); } } } TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; #nullable enable static TypeWithState calculateResultType(TypeWithAnnotations targetTypeWithNullability, bool fromExplicitCast, NullableFlowState resultState, bool isSuppressed, TypeSymbol targetType) { if (isSuppressed) { resultState = NullableFlowState.NotNull; } else if (fromExplicitCast && targetTypeWithNullability.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) { // An explicit cast to a nullable reference type introduces nullability resultState = targetType?.IsTypeParameterDisallowingAnnotationInCSharp8() == true ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } var resultType = TypeWithState.Create(targetType, resultState); return resultType; } static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; switch (state) { case NullableFlowState.MaybeNull: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == true) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && dependsOnTypeParameter(typeParameter1, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } break; case NullableFlowState.MaybeDefault: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == false) { return NullableFlowState.MaybeNull; } break; } return state; } // Converting to a less-derived type (object, interface, type parameter). // If the operand is MaybeNull, the result should be // MaybeNull (if the target type allows) or MaybeDefault otherwise. static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && targetType.Type is TypeParameterSymbol typeParameter2) { bool dependsOn = dependsOnTypeParameter(typeParameter1, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation); Debug.Assert(dependsOn); // If this case fails, add a corresponding test. if (dependsOn) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } return state; } // Converting to a more-derived type (struct, class, type parameter). // If the operand is MaybeNull or MaybeDefault, the result should be // MaybeDefault. static NullableFlowState getUnboxingConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } static NullableFlowState getConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } // If type parameter 1 depends on type parameter 2 (that is, if type parameter 2 appears // in the constraint types of type parameter 1), returns the effective annotation on // type parameter 2 in the constraints of type parameter 1. static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) { if (typeParameter1.Equals(typeParameter2, TypeCompareKind.AllIgnoreOptions)) { annotation = typeParameter1Annotation; return true; } bool dependsOn = false; var combinedAnnotation = NullableAnnotation.Annotated; foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol constraintTypeParameter && dependsOnTypeParameter(constraintTypeParameter, typeParameter2, constraintType.NullableAnnotation, out var constraintAnnotation)) { dependsOn = true; combinedAnnotation = combinedAnnotation.Meet(constraintAnnotation); } } if (dependsOn) { annotation = combinedAnnotation.Join(typeParameter1Annotation); return true; } annotation = default; return false; } NullableFlowState visitNestedTargetTypedConstructs() { switch (conversionOperand) { case BoundConditionalOperator { WasTargetTyped: true } conditional: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(conditional)); var info = ConditionalInfoForConversion[conditional]; Debug.Assert(info.Length == 2); var consequence = conditional.Consequence; (BoundExpression consequenceOperand, Conversion consequenceConversion) = RemoveConversion(consequence, includeExplicitConversions: false); var consequenceRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(consequence, consequenceOperand, consequenceConversion, targetTypeWithNullability, info[0].ResultType, info[0].State, info[0].EndReachable); var alternative = conditional.Alternative; (BoundExpression alternativeOperand, Conversion alternativeConversion) = RemoveConversion(alternative, includeExplicitConversions: false); var alternativeRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(alternative, alternativeOperand, alternativeConversion, targetTypeWithNullability, info[1].ResultType, info[1].State, info[1].EndReachable); ConditionalInfoForConversion.Remove(conditional); return consequenceRValue.State.Join(alternativeRValue.State); } case BoundConvertedSwitchExpression { WasTargetTyped: true } @switch: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(@switch)); var info = ConditionalInfoForConversion[@switch]; Debug.Assert(info.Length == @switch.SwitchArms.Length); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(info.Length); for (int i = 0; i < info.Length; i++) { var (state, armResultType, isReachable) = info[i]; var arm = @switch.SwitchArms[i].Value; var (operand, conversion) = RemoveConversion(arm, includeExplicitConversions: false); resultTypes.Add(ConvertConditionalOperandOrSwitchExpressionArmResult(arm, operand, conversion, targetTypeWithNullability, armResultType, state, isReachable)); } var resultState = BestTypeInferrer.GetNullableState(resultTypes); resultTypes.Free(); ConditionalInfoForConversion.Remove(@switch); return resultState; } case BoundObjectCreationExpression { WasTargetTyped: true }: case BoundUnconvertedObjectCreationExpression: return NullableFlowState.NotNull; case BoundUnconvertedConditionalOperator: case BoundUnconvertedSwitchExpression: return operandType.State; default: throw ExceptionUtilities.UnexpectedValue(conversionOperand.Kind); } } } private TypeWithState VisitUserDefinedConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) { Debug.Assert(!IsConditionalState); Debug.Assert(conversionOperand != null); Debug.Assert(targetTypeWithNullability.HasType); Debug.Assert(diagnosticLocation != null); Debug.Assert(conversion.Kind == ConversionKind.ExplicitUserDefined || conversion.Kind == ConversionKind.ImplicitUserDefined); TypeSymbol targetType = targetTypeWithNullability.Type; // cf. Binder.CreateUserDefinedConversion if (!conversion.IsValid) { var resultType = TypeWithState.Create(targetType, NullableFlowState.NotNull); TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; } // operand -> conversion "from" type // May be distinct from method parameter type for Nullable<T>. operandType = VisitConversion( conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt: diagnosticLocation); // Update method based on operandType: see https://github.com/dotnet/roslyn/issues/29605. // (see NullableReferenceTypesTests.ImplicitConversions_07). var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount == 1); Debug.Assert(operandType.Type is object); var parameter = method.Parameters[0]; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); TypeWithState underlyingOperandType = default; bool isLiftedConversion = false; if (operandType.Type.IsNullableType() && !parameterType.IsNullableType()) { var underlyingOperandTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); underlyingOperandType = underlyingOperandTypeWithAnnotations.ToTypeWithState(); isLiftedConversion = parameterType.Equals(underlyingOperandTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); } // conversion "from" type -> method parameter type NullableFlowState operandState = operandType.State; Location operandLocation = conversionOperand.Syntax.GetLocation(); _ = ClassifyAndVisitConversion( conversionOperand, parameterType, isLiftedConversion ? underlyingOperandType : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterOpt: parameter, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // in the case of a lifted conversion, we assume that the call to the operator occurs only if the argument is not-null if (!isLiftedConversion && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax.Location)) { LearnFromNonNullTest(conversionOperand, ref State); } // method parameter type -> method return type var methodReturnType = method.ReturnTypeWithAnnotations; operandType = GetLiftedReturnTypeIfNecessary(isLiftedConversion, methodReturnType, operandState); if (!isLiftedConversion || operandState.IsNotNull()) { var returnNotNull = operandState.IsNotNull() && method.ReturnNotNullIfParameterNotNull.Contains(parameter.Name); if (returnNotNull) { operandType = operandType.WithNotNullState(); } else { operandType = ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)); } } // method return type -> conversion "to" type // May be distinct from method return type for Nullable<T>. operandType = ClassifyAndVisitConversion( conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // conversion "to" type -> final type // We should only pass fromExplicitCast here. Given the following example: // // class A { public static explicit operator C(A a) => throw null!; } // class C // { // void M() => var c = (C?)new A(); // } // // This final conversion from the method return type "C" to the cast type "C?" is // where we will need to ensure that this is counted as an explicit cast, so that // the resulting operandType is nullable if that was introduced via cast. operandType = ClassifyAndVisitConversion( conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); return operandType; } private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) { if (_snapshotBuilderOpt is null) { return; } var conversionOpt = conversionExpression as BoundConversion; var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode && conversionOpt.Syntax.SpanStart != convertedNode.Syntax.SpanStart) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); TakeIncrementalSnapshot(conversionOpt); conversionOpt = conversionOpt.Operand as BoundConversion; } } private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) { var visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); visitResult = withType(visitResult, conversionOpt.Type); SetAnalyzedNullability(conversionOpt, visitResult); conversionOpt = conversionOpt.Operand as BoundConversion; } static VisitResult withType(VisitResult visitResult, TypeSymbol newType) => new VisitResult(TypeWithState.Create(newType, visitResult.RValueType.State), TypeWithAnnotations.Create(newType, visitResult.LValueType.NullableAnnotation)); } /// <summary> /// Return the return type for a lifted operator, given the nullability state of its operands. /// </summary> private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) { bool typeNeedsLifting = returnType.Type.IsNonNullableValueType(); TypeSymbol type = typeNeedsLifting ? MakeNullableOf(returnType) : returnType.Type; NullableFlowState state = returnType.ToTypeWithState().State.Join(operandState); return TypeWithState.Create(type, state); } private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) { if (isLifted) { var type = typeWithState.Type; if (type?.IsNullableType() == true) { return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); } } return typeWithState; } private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) { return isLifted ? GetLiftedReturnType(returnType, operandState) : returnType.ToTypeWithState(); } private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) { return compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(underlying)); } private TypeWithState ClassifyAndVisitConversion( BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) { Debug.Assert(operandType.Type is object); Debug.Assert(diagnosticLocation != null); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyStandardConversion(null, operandType.Type, targetType.Type, ref discardedUseSiteInfo); if (reportWarnings && !conversion.Exists) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); } } return VisitConversion( conversionOpt: null, conversionOperand: node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings: useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: !fromExplicitCast && reportWarnings, diagnosticLocationOpt: diagnosticLocation); } public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { Debug.Assert(node.Type.IsDelegateType()); if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { VisitMethodGroup(group); var method = node.MethodOpt; if (method is object) { method = CheckMethodGroupReceiverNullability(group, delegateType.DelegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, method, node.IsExtensionMethod); } } SetAnalyzedNullability(group, default); } break; case BoundLambda lambda: { VisitLambda(lambda, delegateType); SetNotNullResult(lambda); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda.UnboundLambda); } } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate } argType: { var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); if (!arg.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, argType.DelegateInvokeMethod(), invokedAsExtensionMethod: false); } // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); } break; default: VisitRvalue(node.Argument); break; } SetNotNullResult(node); return null; } public override BoundNode? VisitMethodGroup(BoundMethodGroup node) { Debug.Assert(!IsConditionalState); var receiverOpt = node.ReceiverOpt; if (receiverOpt != null) { VisitRvalue(receiverOpt); // Receiver nullability is checked when applying the method group conversion, // when we have a specific method, to avoid reporting null receiver warnings // for extension method delegates. Here, store the receiver state for that check. SetMethodGroupReceiverNullability(receiverOpt, ResultType); } SetNotNullResult(node); return null; } private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) { if (receiverOpt != null && _methodGroupReceiverMapOpt != null && _methodGroupReceiverMapOpt.TryGetValue(receiverOpt, out type)) { return true; } else { type = default; return false; } } private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) { _methodGroupReceiverMapOpt ??= PooledDictionary<BoundExpression, TypeWithState>.GetInstance(); _methodGroupReceiverMapOpt[receiver] = type; } private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray<ParameterSymbol> parameters, MethodSymbol method, bool invokedAsExtensionMethod) { var receiverOpt = group.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { var syntax = group.Syntax; if (!invokedAsExtensionMethod) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) { var arguments = ArrayBuilder<BoundExpression>.GetInstance(); if (invokedAsExtensionMethod) { arguments.Add(CreatePlaceholderIfNecessary(receiverOpt, receiverType.ToTypeWithAnnotations(compilation))); } // Create placeholders for the arguments. (See Conversions.GetDelegateArguments() // which is used for that purpose in initial binding.) foreach (var parameter in parameters) { var parameterType = parameter.TypeWithAnnotations; arguments.Add(new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, parameter), parameterType.NullableAnnotation, parameterType.Type)); } Debug.Assert(_binder is object); method = InferMethodTypeArguments(method, arguments.ToImmutableAndFree(), argumentRefKindsOpt: default, argsToParamsOpt: default, expanded: false); } if (invokedAsExtensionMethod) { CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], receiverType); } else { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } if (ConstraintsHelper.RequiresChecking(method)) { CheckMethodConstraints(syntax, method); } } return method; } public override BoundNode? VisitLambda(BoundLambda node) { // Note: actual lambda analysis happens after this call (primarily in VisitConversion). // Here we just indicate that a lambda expression produces a non-null value. SetNotNullResult(node); return null; } private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional<LocalState> initialState = default) { Debug.Assert(delegateTypeOpt?.IsDelegateType() != false); var delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt is object) { SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt!); } AnalyzeLocalFunctionOrLambda( node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); } private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) { if (delegateInvokeMethod is null) { useDelegateInvokeParameterTypes = false; useDelegateInvokeReturnType = false; } else { var unboundLambda = lambda.UnboundLambda; useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out _, out _); } } public override BoundNode? VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. // Analyze the body to report any additional warnings. var lambda = node.BindForErrorRecovery(); VisitLambda(lambda, delegateTypeOpt: null); SetNotNullResult(node); return null; } public override BoundNode? VisitThisReference(BoundThisReference node) { VisitThisOrBaseReference(node); return null; } private void VisitThisOrBaseReference(BoundExpression node) { var rvalueResult = TypeWithState.Create(node.Type, NullableFlowState.NotNull); var lvalueResult = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); SetResult(node, rvalueResult, lvalueResult); } public override BoundNode? VisitParameter(BoundParameter node) { var parameter = node.ParameterSymbol; int slot = GetOrCreateSlot(parameter); var parameterType = GetDeclaredParameterResult(parameter); var typeWithState = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations); SetResult(node, GetAdjustedResult(typeWithState, slot), parameterType); return null; } public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { Debug.Assert(!IsConditionalState); var left = node.Left; switch (left) { // when binding initializers, we treat assignments to auto-properties or field-like events as direct assignments to the underlying field. // in order to track member state based on these initializers, we need to see the assignment in terms of the associated member case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: PropertySymbol autoProperty } } fieldAccess: left = new BoundPropertyAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, autoProperty, LookupResultKind.Viable, autoProperty.Type, fieldAccess.HasErrors); break; case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: EventSymbol @event } } fieldAccess: left = new BoundEventAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, @event, isUsableAsField: true, LookupResultKind.Viable, @event.Type, fieldAccess.HasErrors); break; } var right = node.Right; VisitLValue(left); // we may enter a conditional state for error scenarios on the LHS. Unsplit(); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to an Add method. (Note that assignment // of non-field-like events uses BoundEventAssignmentOperator // rather than BoundAssignmentOperator.) VisitRvalue(right); SetNotNullResult(node); } else { TypeWithState rightState; if (!node.IsRef) { var discarded = left is BoundDiscardExpression; rightState = VisitOptionalImplicitConversion(right, targetTypeOpt: discarded ? default : leftLValueType, UseLegacyWarnings(left, leftLValueType), trackMembers: true, AssignmentKind.Assignment); } else { rightState = VisitRefExpression(right, leftLValueType); } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(rightState, leftAnnotations, right.Syntax.Location); AdjustSetValue(left, ref rightState); TrackNullableStateForAssignment(right, leftLValueType, MakeSlot(left), rightState, MakeSlot(right)); if (left is BoundDiscardExpression) { var lvalueType = rightState.ToTypeWithAnnotations(compilation); SetResult(left, rightState, lvalueType, isLvalue: true); SetResult(node, rightState, lvalueType); } else { SetResult(node, TypeWithState.Create(leftLValueType.Type, rightState.State), leftLValueType); } } return null; } private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) { var type = property.TypeWithAnnotations; var annotations = IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : property.GetFlowAnalysisAnnotations(); var lValueType = ApplyLValueAnnotations(type, annotations); if (lValueType.NullableAnnotation.IsOblivious() || !lValueType.CanBeAssignedNull) { return false; } var rValueType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), annotations); return rValueType.IsNotNull; } /// <summary> /// When the allowed output of a property/indexer is not-null but the allowed input is maybe-null, we store a not-null value instead. /// This way, assignment of a legal input value results in a legal output value. /// This adjustment doesn't apply to oblivious properties/indexers. /// </summary> private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) { var property = left switch { BoundPropertyAccess propAccess => propAccess.PropertySymbol, BoundIndexerAccess indexerAccess => indexerAccess.Indexer, _ => null }; if (property is not null && IsPropertyOutputMoreStrictThanInput(property)) { rightState = rightState.WithNotNullState(); } } private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = expr switch { BoundPropertyAccess property => property.PropertySymbol.GetFlowAnalysisAnnotations(), BoundIndexerAccess indexer => indexer.Indexer.GetFlowAnalysisAnnotations(), BoundFieldAccess field => getFieldAnnotations(field.FieldSymbol), BoundObjectInitializerMember { MemberSymbol: PropertySymbol prop } => prop.GetFlowAnalysisAnnotations(), BoundObjectInitializerMember { MemberSymbol: FieldSymbol field } => getFieldAnnotations(field), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); static FlowAnalysisAnnotations getFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } } private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) { var annotations = FlowAnalysisAnnotations.None; if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen count as MaybeNull annotations |= FlowAnalysisAnnotations.AllowNull; } if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNullWhenTrue and NotNullWhenFalse don't count on their own. Only NotNull (ie. both flags) matters. annotations |= FlowAnalysisAnnotations.DisallowNull; } return annotations; } private static bool UseLegacyWarnings(BoundExpression expr, TypeWithAnnotations exprType) { switch (expr.Kind) { case BoundKind.Local: return expr.GetRefKind() == RefKind.None; case BoundKind.Parameter: RefKind kind = ((BoundParameter)expr).ParameterSymbol.RefKind; return kind == RefKind.None; default: return false; } } public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return VisitDeconstructionAssignmentOperator(node, rightResultOpt: null); } private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) { var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; _disableNullabilityAnalysis = true; var left = node.Left; var right = node.Right; var variables = GetDeconstructionAssignmentVariables(left); if (node.HasErrors) { // In the case of errors, simply visit the right as an r-value to update // any nullability state even though deconstruction is skipped. VisitRvalue(right.Operand); } else { VisitDeconstructionArguments(variables, right.Conversion, right.Operand, rightResultOpt); } variables.FreeAll(v => v.NestedVariables); // https://github.com/dotnet/roslyn/issues/33011: Result type should be inferred and the constraints should // be re-verified. Even though the standard tuple type has no constraints we support that scenario. Constraints_78 // has a test for this case that should start failing when this is fixed. SetNotNullResult(node); _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; return null; } private void VisitDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) { Debug.Assert(conversion.Kind == ConversionKind.Deconstruction); if (!conversion.DeconstructionInfo.IsDefault) { VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); } else { VisitTupleDeconstructionArguments(variables, conversion.UnderlyingConversions, right); } } private void VisitDeconstructMethodArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) { VisitRvalue(right); // If we were passed an explicit right result, use that rather than the visited result if (rightResultOpt.HasValue) { SetResultType(right, rightResultOpt.Value); } var rightResult = ResultType; var invocation = conversion.DeconstructionInfo.Invocation as BoundCall; var deconstructMethod = invocation?.Method; if (deconstructMethod is object) { Debug.Assert(invocation is object); Debug.Assert(rightResult.Type is object); int n = variables.Count; if (!invocation.InvokedAsExtensionMethod) { _ = CheckPossibleNullReceiver(right); // update the deconstruct method with any inferred type parameters of the containing type if (deconstructMethod.OriginalDefinition != deconstructMethod) { deconstructMethod = deconstructMethod.OriginalDefinition.AsMember((NamedTypeSymbol)rightResult.Type); } } else { if (deconstructMethod.IsGenericMethod) { // re-infer the deconstruct parameters based on the 'this' parameter ArrayBuilder<BoundExpression> placeholderArgs = ArrayBuilder<BoundExpression>.GetInstance(n + 1); placeholderArgs.Add(CreatePlaceholderIfNecessary(right, rightResult.ToTypeWithAnnotations(compilation))); for (int i = 0; i < n; i++) { placeholderArgs.Add(new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); } deconstructMethod = InferMethodTypeArguments(deconstructMethod, placeholderArgs.ToImmutableAndFree(), invocation.ArgumentRefKindsOpt, invocation.ArgsToParamsOpt, invocation.Expanded); // check the constraints remain valid with the re-inferred parameter types if (ConstraintsHelper.RequiresChecking(deconstructMethod)) { CheckMethodConstraints(invocation.Syntax, deconstructMethod); } } } var parameters = deconstructMethod.Parameters; int offset = invocation.InvokedAsExtensionMethod ? 1 : 0; Debug.Assert(parameters.Length - offset == n); if (invocation.InvokedAsExtensionMethod) { // Check nullability for `this` parameter var argConversion = RemoveConversion(invocation.Arguments[0], includeExplicitConversions: false).conversion; CheckExtensionMethodThisNullability(right, argConversion, deconstructMethod.Parameters[0], rightResult); } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var underlyingConversion = conversion.UnderlyingConversions[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { var nestedRight = CreatePlaceholderIfNecessary(invocation.Arguments[i + offset], parameter.TypeWithAnnotations); VisitDeconstructionArguments(nestedVariables, underlyingConversion, right: nestedRight); } else { VisitArgumentConversionAndInboundAssignmentsAndPreConditions(conversionOpt: null, variable.Expression, underlyingConversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), extensionMethodThisArgument: false); } } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var nestedVariables = variable.NestedVariables; if (nestedVariables == null) { VisitArgumentOutboundAssignmentsAndPostConditions( variable.Expression, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetRValueAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), notNullParametersOpt: null, compareExchangeInfoOpt: default); } } } } private void VisitTupleDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<Conversion> conversions, BoundExpression right) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var underlyingConversion = conversions[i]; var rightPart = rightParts[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { VisitDeconstructionArguments(nestedVariables, underlyingConversion, rightPart); } else { var lvalueType = variable.Type; var leftAnnotations = GetLValueAnnotations(variable.Expression); lvalueType = ApplyLValueAnnotations(lvalueType, leftAnnotations); TypeWithState operandType; TypeWithState valueType; int valueSlot; if (underlyingConversion.IsIdentity) { if (variable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } local) { // when the LHS is a var declaration, we can just visit the right part to infer the type valueType = operandType = VisitRvalueWithState(rightPart); _variables.SetType(local.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); } else { operandType = default; valueType = VisitOptionalImplicitConversion(rightPart, lvalueType, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } valueSlot = MakeSlot(rightPart); } else { operandType = VisitRvalueWithState(rightPart); valueType = VisitConversion( conversionOpt: null, rightPart, underlyingConversion, lvalueType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment, reportTopLevelWarnings: true, reportRemainingWarnings: true, trackMembers: false); valueSlot = -1; } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(valueType, leftAnnotations, right.Syntax.Location); int targetSlot = MakeSlot(variable.Expression); AdjustSetValue(variable.Expression, ref valueType); TrackNullableStateForAssignment(rightPart, lvalueType, targetSlot, valueType, valueSlot); // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (targetSlot > 0 && underlyingConversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(lvalueType.Type, operandType.Type, out TypeWithAnnotations underlyingType)) { valueSlot = MakeSlot(rightPart); if (valueSlot > 0) { var valueBeforeNullableWrapping = TypeWithState.Create(underlyingType.Type, NullableFlowState.NotNull); TrackNullableStateOfNullableValue(targetSlot, lvalueType.Type, rightPart, valueBeforeNullableWrapping, valueSlot); } } } } } private readonly struct DeconstructionVariable { internal readonly BoundExpression Expression; internal readonly TypeWithAnnotations Type; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) { Expression = expression; Type = type; NestedVariables = null; } internal DeconstructionVariable(BoundExpression expression, ArrayBuilder<DeconstructionVariable> nestedVariables) { Expression = expression; Type = default; NestedVariables = nestedVariables; } } private ArrayBuilder<DeconstructionVariable> GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) { var arguments = tuple.Arguments; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(arguments.Length); foreach (var argument in arguments) { builder.Add(getDeconstructionAssignmentVariable(argument)); } return builder; DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); default: VisitLValue(expr); return new DeconstructionVariable(expr, LvalueResultType); } } } /// <summary> /// Return the sub-expressions for the righthand side of a deconstruction /// assignment. cf. LocalRewriter.GetRightParts. /// </summary> private ImmutableArray<BoundExpression> GetDeconstructionRightParts(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return ((BoundTupleExpression)expr).Arguments; case BoundKind.Conversion: { var conv = (BoundConversion)expr; switch (conv.ConversionKind) { case ConversionKind.Identity: case ConversionKind.ImplicitTupleLiteral: return GetDeconstructionRightParts(conv.Operand); } } break; } if (expr.Type is NamedTypeSymbol { IsTupleType: true } tupleType) { // https://github.com/dotnet/roslyn/issues/33011: Should include conversion.UnderlyingConversions[i]. // For instance, Boxing conversions (see Deconstruction_ImplicitBoxingConversion_02) and // ImplicitNullable conversions (see Deconstruction_ImplicitNullableConversion_02). var fields = tupleType.TupleElements; return fields.SelectAsArray((f, e) => (BoundExpression)new BoundFieldAccess(e.Syntax, e, f, constantValueOpt: null), expr); } throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) { Debug.Assert(!IsConditionalState); var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 // https://github.com/dotnet/roslyn/issues/29961 Update conversion method based on operand type. if (node.OperandConversion.IsUserDefined && node.OperandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = node.OperandConversion.Method.ReturnTypeWithAnnotations; } else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } else { // Either a built-in increment, or an error case. targetTypeOfOperandConversion = default; } TypeWithState resultOfOperandConversionType; if (targetTypeOfOperandConversion.HasType) { // https://github.com/dotnet/roslyn/issues/29961 Should something special be done for targetTypeOfOperandConversion for lifted case? resultOfOperandConversionType = VisitConversion( conversionOpt: null, node.Operand, node.OperandConversion, targetTypeOfOperandConversion, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true); } else { resultOfOperandConversionType = operandType; } TypeWithState resultOfIncrementType; if (incrementOperator is null) { resultOfIncrementType = resultOfOperandConversionType; } else { resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); resultOfIncrementType = VisitConversion( conversionOpt: null, node, node.ResultConversion, operandTypeWithAnnotations, resultOfIncrementType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // https://github.com/dotnet/roslyn/issues/29961 Check node.Type.IsErrorType() instead? if (!node.HasErrors) { var op = node.OperatorKind.Operator(); TypeWithState resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType; SetResultType(node, resultType); setResult = true; TrackNullableStateForAssignment(node, targetType: operandLvalue, targetSlot: MakeSlot(node.Operand), valueType: resultOfIncrementType); } } if (!setResult) { SetNotNullResult(node); } return null; } public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { var left = node.Left; var right = node.Right; Visit(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = declaredType; TypeWithState leftResultType = ResultType; Debug.Assert(!IsConditionalState); TypeWithState leftOnRightType = GetAdjustedResult(leftResultType, MakeSlot(node.Left)); // https://github.com/dotnet/roslyn/issues/29962 Update operator based on inferred argument types. if ((object)node.Operator.LeftType != null) { // https://github.com/dotnet/roslyn/issues/29962 Ignoring top-level nullability of operator left parameter. leftOnRightType = VisitConversion( conversionOpt: null, node.Left, node.LeftConversion, TypeWithAnnotations.Create(node.Operator.LeftType), leftOnRightType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: true); } else { leftOnRightType = default; } TypeWithState resultType; TypeWithState rightType = VisitRvalueWithState(right); if ((object)node.Operator.ReturnType != null) { if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(node.Left); leftLValueType = ApplyLValueAnnotations(leftLValueType, leftAnnotations); resultType = VisitConversion( conversionOpt: null, node, node.FinalConversion, leftLValueType, resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, leftAnnotations, node.Syntax.Location); } else { resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); } AdjustSetValue(left, ref resultType); TrackNullableStateForAssignment(node, leftLValueType, MakeSlot(node.Left), resultType); SetResultType(node, resultType); return null; } public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { var initializer = node.Expression; if (initializer.Kind == BoundKind.AddressOfOperator) { initializer = ((BoundAddressOfOperator)initializer).Operand; } VisitRvalue(initializer); if (node.Expression.Kind == BoundKind.AddressOfOperator) { SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); } SetNotNullResult(node); return null; } public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) { Visit(node.Operand); SetNotNullResult(node); return null; } private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) { var paramType = parameter.TypeWithAnnotations; ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) { ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); } } private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); } /// <summary> /// Report warning passing argument where nested nullability does not match /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`). /// </summary> private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) { ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); } private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) { ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, parameterOpt?.Type.IsNonNullableValueType() == true && parameterType.IsNullableType() ? parameterOpt.Type : parameterType, // Compensate for operator lifting GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); } private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) { return _variables.TryGetType(local, out TypeWithAnnotations type) ? type : local.TypeWithAnnotations; } private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) { return _variables.TryGetType(parameter, out TypeWithAnnotations type) ? type : parameter.TypeWithAnnotations; } public override BoundNode? VisitBaseReference(BoundBaseReference node) { VisitThisOrBaseReference(node); return null; } public override BoundNode? VisitFieldAccess(BoundFieldAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); return null; } public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; var updatedMember = VisitMemberAccess(node, node.ReceiverOpt, property); if (!IsAnalyzingAttribute) { if (_expressionIsRead) { ApplyMemberPostConditions(node.ReceiverOpt, property.GetMethod); } else { ApplyMemberPostConditions(node.ReceiverOpt, property.SetMethod); } } SetUpdatedSymbol(node, property, updatedMember); return null; } public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) { var receiverOpt = node.ReceiverOpt; var receiverType = VisitRvalueWithState(receiverOpt).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); var indexer = node.Indexer; if (receiverType is object) { // Update indexer based on inferred receiver type. indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); SetUpdatedSymbol(node, node.Indexer, indexer); return null; } public override BoundNode? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { BoundExpression receiver = node.Receiver; var receiverType = VisitRvalueWithState(receiver).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitRvalue(node.Argument); var patternSymbol = node.PatternSymbol; if (receiverType is object) { patternSymbol = AsMemberOfType(receiverType, patternSymbol); } SetLvalueResultType(node, patternSymbol.GetTypeOrReturnType()); SetUpdatedSymbol(node, node.PatternSymbol, patternSymbol); return null; } public override BoundNode? VisitEventAccess(BoundEventAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); return null; } private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) { Debug.Assert(!IsConditionalState); var receiverType = (receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default; SpecialMember? nullableOfTMember = null; if (member.RequiresInstanceReceiver()) { member = AsMemberOfType(receiverType.Type, member); nullableOfTMember = GetNullableOfTMember(member); // https://github.com/dotnet/roslyn/issues/30598: For l-values, mark receiver as not null // after RHS has been visited, and only if the receiver has not changed. bool skipReceiverNullCheck = nullableOfTMember != SpecialMember.System_Nullable_T_get_Value; _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType: !skipReceiverNullCheck); } var type = member.GetTypeOrReturnType(); var memberAnnotations = GetRValueAnnotations(member); var resultType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), memberAnnotations); // We are supposed to track information for the node. Use whatever we managed to // accumulate so far. if (PossiblyNullableType(resultType.Type)) { int slot = MakeMemberSlot(receiverOpt, member); if (this.State.HasValue(slot)) { var state = this.State[slot]; resultType = TypeWithState.Create(resultType.Type, state); } } Debug.Assert(!IsConditionalState); if (nullableOfTMember == SpecialMember.System_Nullable_T_get_HasValue && !(receiverOpt is null)) { int containingSlot = MakeSlot(receiverOpt); if (containingSlot > 0) { Split(); this.StateWhenTrue[containingSlot] = NullableFlowState.NotNull; } } SetResult(node, resultType, type); return member; } private SpecialMember? GetNullableOfTMember(Symbol member) { if (member.Kind == SymbolKind.Property) { var getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; if ((object)getMethod != null && getMethod.ContainingType.SpecialType == SpecialType.System_Nullable_T) { if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { return SpecialMember.System_Nullable_T_get_Value; } if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue)) { return SpecialMember.System_Nullable_T_get_HasValue; } } } return null; } private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) { Debug.Assert(containingType.IsNullableType()); Debug.Assert(TypeSymbol.Equals(NominalSlotType(containingSlot), containingType, TypeCompareKind.ConsiderEverything2)); var getValue = (MethodSymbol)compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value); valueProperty = getValue?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; return (valueProperty is null) ? -1 : GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty: forceSlotEvenIfEmpty); } protected override void VisitForEachExpression(BoundForEachStatement node) { if (node.Expression.Kind != BoundKind.Conversion) { // If we're in this scenario, there was a binding error, and we should suppress any further warnings. Debug.Assert(node.HasErrors); VisitRvalue(node.Expression); return; } var (expr, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(node.Expression, expr); // There are 7 ways that a foreach can be created: // 1. The collection type is an array type. For this, initial binding will generate an implicit reference conversion to // IEnumerable, and we do not need to do any reinferring of enumerators here. // 2. The collection type is dynamic. For this we do the same as 1. // 3. The collection type implements the GetEnumerator pattern. For this, there is an identity conversion. Because // this identity conversion uses nested types from initial binding, we cannot trust them and must instead use // the type of the expression returned from VisitResult to reinfer the enumerator information. // 4. The collection type implements IEnumerable<T>. Only a few cases can hit this without being caught by number 3, // such as a type with a private implementation of IEnumerable<T>, or a type parameter constrained to that type. // In these cases, there will be an implicit conversion to IEnumerable<T>, but this will use types from // initial binding. For this scenario, we need to look through the list of implemented interfaces on the type and // find the version of IEnumerable<T> that it has after nullable analysis, as type substitution could have changed // nested nullability of type parameters. See ForEach_22 for a concrete example of this. // 5. The collection type implements IEnumerable (non-generic). Because this version isn't generic, we don't need to // do any reinference, and the existing conversion can stand as is. // 6. The target framework's System.String doesn't implement IEnumerable. This is a compat case: System.String normally // does implement IEnumerable, but there are certain target frameworks where this isn't the case. The compiler will // still emit code for foreach in these scenarios. // 7. The collection type implements the GetEnumerator pattern via an extension GetEnumerator. For this, there will be // conversion to the parameter of the extension method. // 8. Some binding error occurred, and some other error has already been reported. Usually this doesn't have any kind // of conversion on top, but if there was an explicit conversion in code then we could get past the initial check // for a BoundConversion node. var resultTypeWithState = VisitRvalueWithState(expr); var resultType = resultTypeWithState.Type; Debug.Assert(resultType is object); SetAnalyzedNullability(expr, _visitResult); TypeWithAnnotations targetTypeWithAnnotations; MethodSymbol? reinferredGetEnumeratorMethod = null; if (node.EnumeratorInfoOpt?.GetEnumeratorInfo is { Method: { IsExtensionMethod: true, Parameters: var parameters } } enumeratorMethodInfo) { // this is case 7 // We do not need to do this same analysis for non-extension methods because they do not have generic parameters that // can be inferred from usage like extension methods can. We don't warn about default arguments at the call site, so // there's nothing that can be learned from the non-extension case. var (method, results, _) = VisitArguments( node, enumeratorMethodInfo.Arguments, refKindsOpt: default, parameters, argsToParamsOpt: enumeratorMethodInfo.ArgsToParamsOpt, defaultArguments: enumeratorMethodInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, enumeratorMethodInfo.Method); targetTypeWithAnnotations = results[0].LValueType; reinferredGetEnumeratorMethod = method; } else if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && resultType.SpecialType == SpecialType.System_String)) { // This is case 3 or 6. targetTypeWithAnnotations = resultTypeWithState.ToTypeWithAnnotations(compilation); } else if (conversion.IsImplicit) { bool isAsync = node.AwaitOpt != null; if (node.Expression.Type!.SpecialType == SpecialType.System_Collections_IEnumerable) { // If this is a conversion to IEnumerable (non-generic), nothing to do. This is cases 1, 2, and 5. targetTypeWithAnnotations = TypeWithAnnotations.Create(node.Expression.Type); } else if (ForEachLoopBinder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) { // This is case 4. We need to look for the IEnumerable<T> that this reinferred expression implements, // so that we pick up any nested type substitutions that could have occurred. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; targetTypeWithAnnotations = TypeWithAnnotations.Create(ForEachLoopBinder.GetIEnumerableOfT(resultType, isAsync, compilation, ref discardedUseSiteInfo, out bool foundMultiple)); Debug.Assert(!foundMultiple); Debug.Assert(targetTypeWithAnnotations.HasType); } else { // This is case 8. There was not a successful binding, as a successful binding will _always_ generate one of the // above conversions. Just return, as we want to suppress further errors. return; } } else { // This is also case 8. return; } var convertedResult = VisitConversion( GetConversionIfApplicable(node.Expression, expr), expr, conversion, targetTypeWithAnnotations, resultTypeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); bool reportedDiagnostic = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method is { IsExtensionMethod: true } ? false : CheckPossibleNullReceiver(expr); SetAnalyzedNullability(node.Expression, new VisitResult(convertedResult, convertedResult.ToTypeWithAnnotations(compilation))); TypeWithState currentPropertyGetterTypeWithState; if (node.EnumeratorInfoOpt is null) { currentPropertyGetterTypeWithState = default; } else if (resultType is ArrayTypeSymbol arrayType) { // Even though arrays use the IEnumerator pattern, we use the array element type as the foreach target type, so // directly get our source type from there instead of doing method reinference. currentPropertyGetterTypeWithState = arrayType.ElementTypeWithAnnotations.ToTypeWithState(); } else if (resultType.SpecialType == SpecialType.System_String) { // There are frameworks where System.String does not implement IEnumerable, but we still lower it to a for loop // using the indexer over the individual characters anyway. So the type must be not annotated char. currentPropertyGetterTypeWithState = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); } else { // Reinfer the return type of the node.Expression.GetEnumerator().Current property, so that if // the collection changed nested generic types we pick up those changes. reinferredGetEnumeratorMethod ??= (MethodSymbol)AsMemberOfType(convertedResult.Type, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); var enumeratorReturnType = GetReturnTypeWithState(reinferredGetEnumeratorMethod); if (enumeratorReturnType.State != NullableFlowState.NotNull) { if (!reportedDiagnostic && !(node.Expression is BoundConversion { Operand: { IsSuppressed: true } })) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, expr.Syntax.GetLocation()); } } var currentPropertyGetter = (MethodSymbol)AsMemberOfType(enumeratorReturnType.Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); // Analyze `await MoveNextAsync()` if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) { var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); Visit(awaitMoveNextInfo); _awaitablePlaceholdersOpt.Remove(moveNextPlaceholder); } // Analyze `await DisposeAsync()` if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) { var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; bool addedPlaceholder = false; if (node.EnumeratorInfoOpt.PatternDisposeInfo is { Method: var originalDisposeMethod }) // no statically known Dispose method if doing a runtime check { Debug.Assert(disposalPlaceholder is not null); var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, originalDisposeMethod); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { _awaitablePlaceholdersOpt!.Remove(disposalPlaceholder!); } } } SetResultType(expression: null, currentPropertyGetterTypeWithState); } public override void VisitForEachIterationVariables(BoundForEachStatement node) { // ResultType should have been set by VisitForEachExpression, called just before this. var sourceState = node.EnumeratorInfoOpt == null ? default : ResultType; TypeWithAnnotations sourceType = sourceState.ToTypeWithAnnotations(compilation); #pragma warning disable IDE0055 // Fix formatting var variableLocation = node.Syntax switch { ForEachStatementSyntax statement => statement.Identifier.GetLocation(), ForEachVariableStatementSyntax variableStatement => variableStatement.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Syntax) }; #pragma warning restore IDE0055 // Fix formatting if (node.DeconstructionOpt is object) { var assignment = node.DeconstructionOpt.DeconstructionAssignment; // Visit the assignment as a deconstruction with an explicit type VisitDeconstructionAssignmentOperator(assignment, sourceState.HasNullType ? (TypeWithState?)null : sourceState); // https://github.com/dotnet/roslyn/issues/35010: if the iteration variable is a tuple deconstruction, we need to put something in the tree Visit(node.IterationVariableType); } else { Visit(node.IterationVariableType); foreach (var iterationVariable in node.IterationVariables) { var state = NullableFlowState.NotNull; if (!sourceState.HasNullType) { TypeWithAnnotations destinationType = iterationVariable.TypeWithAnnotations; TypeWithState result = sourceState; TypeWithState resultForType = sourceState; if (iterationVariable.IsRef) { // foreach (ref DestinationType variable in collection) if (IsNullabilityMismatch(sourceType, destinationType)) { var foreachSyntax = (ForEachStatementSyntax)node.Syntax; ReportNullabilityMismatchInAssignment(foreachSyntax.Type, sourceType, destinationType); } } else if (iterationVariable is SourceLocalSymbol { IsVar: true }) { // foreach (var variable in collection) destinationType = sourceState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(iterationVariable, destinationType); resultForType = destinationType.ToTypeWithState(); } else { // foreach (DestinationType variable in collection) // and asynchronous variants var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion conversion = node.ElementConversion.Kind == ConversionKind.UnsetConversionKind ? _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo) : node.ElementConversion; result = VisitConversion( conversionOpt: null, conversionOperand: node.IterationVariableType, conversion, destinationType, sourceState, checkConversion: true, fromExplicitCast: !conversion.IsImplicit, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, reportTopLevelWarnings: true, reportRemainingWarnings: true, diagnosticLocationOpt: variableLocation); } // In non-error cases we'll only run this loop a single time. In error cases we'll set the nullability of the VariableType multiple times, but at least end up with something SetAnalyzedNullability(node.IterationVariableType, new VisitResult(resultForType, destinationType), isLvalue: true); state = result.State; } int slot = GetOrCreateSlot(iterationVariable); if (slot > 0) { this.State[slot] = state; } } } } public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { var result = base.VisitFromEndIndexExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Should be handled by VisitObjectCreationExpression. throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { SetNotNullResult(node); return null; } public override BoundNode? VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { // https://github.com/dotnet/roslyn/issues/35042, we need to implement similar workarounds for object, collection, and dynamic initializers. if (child is BoundLambda lambda) { TakeIncrementalSnapshot(lambda); VisitLambda(lambda, delegateTypeOpt: null); VisitRvalueEpilogue(lambda); } else { VisitRvalue(child as BoundExpression); } } var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return null; } public override BoundNode? VisitTypeExpression(BoundTypeExpression node) { var result = base.VisitTypeExpression(node); if (node.BoundContainingTypeOpt != null) { VisitTypeExpression(node.BoundContainingTypeOpt); } SetNotNullResult(node); return result; } public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // These should not appear after initial binding except in error cases. var result = base.VisitTypeOrValueExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) { Debug.Assert(!IsConditionalState); TypeWithState resultType; switch (node.OperatorKind) { case UnaryOperatorKind.BoolLogicalNegation: Visit(node.Operand); if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicTrue: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicLogicalNegation: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); // If the state is split, the result is `bool` at runtime and we invert it here. if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; default: if (node.OperatorKind.IsUserDefined() && node.MethodOpt is MethodSymbol method && method.ParameterCount == 1) { var (operand, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); VisitRvalue(operand); var operandResult = ResultType; bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( node.Operand as BoundConversion, operand, conversion, parameter.TypeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter); resultType = GetLiftedReturnTypeIfNecessary(isLifted, method.ReturnTypeWithAnnotations, operandResult.State); SetUpdatedSymbol(node, node.MethodOpt, method); } else { VisitRvalue(node.Operand); resultType = adjustForLifting(ResultType); } break; } SetResultType(node, resultType); return null; TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) { var result = base.VisitPointerElementAccess(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); SetNotNullResult(node); return null; } public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) { var result = base.VisitMakeRefOperator(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) { var result = base.VisitRefValueOperator(node); var type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetLvalueResultType(node, type); return result; } private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) { if (node.OperatorKind.IsLifted()) { // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator // Should this use the updated flow type and state? How should it compute nullability? return TypeWithState.Create(node.Type, NullableFlowState.NotNull); } // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) { return GetReturnTypeWithState(node.LogicalOperator); } else { return default; } } protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { Debug.Assert(!IsConditionalState); TypeWithState leftType = ResultType; // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. MethodSymbol? logicalOperator = null; MethodSymbol? trueFalseOperator = null; BoundExpression? left = null; switch (node.Kind) { case BoundKind.BinaryOperator: Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); break; case BoundKind.UserDefinedConditionalLogicalOperator: var binary = (BoundUserDefinedConditionalLogicalOperator)node; if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) { logicalOperator = binary.LogicalOperator; left = binary.Left; trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) { trueFalseOperator = null; } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } Debug.Assert(trueFalseOperator is null || logicalOperator is object); Debug.Assert(logicalOperator is null || left is object); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if (trueFalseOperator is object) { ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); } if (logicalOperator is object) { ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); } Visit(right); TypeWithState rightType = ResultType; SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); if (logicalOperator is object) { ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); } AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse); } private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) { return node switch { BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), _ => throw ExceptionUtilities.UnexpectedValue(node) }; } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { var result = base.VisitAwaitExpression(node); var awaitableInfo = node.AwaitableInfo; var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(placeholder); if (node.Type.IsValueType || node.HasErrors || awaitableInfo.GetResult is null) { SetNotNullResult(node); } else { // It is possible for the awaiter type returned from GetAwaiter to not be a named type. e.g. it could be a type parameter. // Proper handling of this is additional work which only benefits a very uncommon scenario, // so we will just use the originally bound GetResult method in this case. var getResult = awaitableInfo.GetResult; var reinferredGetResult = _visitResult.RValueType.Type is NamedTypeSymbol taskAwaiterType ? getResult.OriginalDefinition.AsMember(taskAwaiterType) : getResult; SetResultType(node, reinferredGetResult.ReturnTypeWithAnnotations.ToTypeWithState()); } return result; } public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) { var result = base.VisitTypeOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitMethodInfo(BoundMethodInfo node) { var result = base.VisitMethodInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitFieldInfo(BoundFieldInfo node) { var result = base.VisitFieldInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { // Can occur in error scenarios and lambda scenarios var result = base.VisitDefaultLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); return result; } public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) { Debug.Assert(!this.IsConditionalState); var result = base.VisitDefaultExpression(node); TypeSymbol type = node.Type; if (EmptyStructTypeCache.IsTrackableStructType(type)) { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isDefaultValue: true); } } // https://github.com/dotnet/roslyn/issues/33344: this fails to produce an updated tuple type for a default expression // (should produce nullable element types for those elements that are of reference types) SetResultType(node, TypeWithState.ForType(type)); return result; } public override BoundNode? VisitIsOperator(BoundIsOperator node) { Debug.Assert(!this.IsConditionalState); var operand = node.Operand; var typeExpr = node.TargetType; VisitPossibleConditionalAccess(operand, out var conditionalStateWhenNotNull); Unsplit(); LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean); SetConditionalState(stateWhenNotNull, State); if (typeExpr.Type?.SpecialType == SpecialType.System_Object) { LearnFromNullTest(operand, ref StateWhenFalse); } VisitTypeExpression(typeExpr); SetNotNullResult(node); return null; } public override BoundNode? VisitAsOperator(BoundAsOperator node) { var argumentType = VisitRvalueWithState(node.Operand); NullableFlowState resultState = NullableFlowState.NotNull; var type = node.Type; if (type.CanContainNull()) { switch (node.Conversion.Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: resultState = argumentType.State; break; default: resultState = NullableFlowState.MaybeDefault; break; } } VisitTypeExpression(node.TargetType); SetResultType(node, TypeWithState.Create(type, resultState)); return null; } public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) { var result = base.VisitSizeOfOperator(node); VisitTypeExpression(node.SourceType); SetNotNullResult(node); return result; } public override BoundNode? VisitArgList(BoundArgList node) { var result = base.VisitArgList(node); Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle); SetNotNullResult(node); return result; } public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; } public override BoundNode? VisitLiteral(BoundLiteral node) { Debug.Assert(!IsConditionalState); var result = base.VisitLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, node.Type?.CanContainNull() != false && node.ConstantValue?.IsNull == true ? NullableFlowState.MaybeDefault : NullableFlowState.NotNull)); return result; } public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var result = base.VisitPreviousSubmissionReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { var result = base.VisitHostObjectMemberReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) { var result = base.VisitPseudoVariable(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeExpression(BoundRangeExpression node) { var result = base.VisitRangeExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeVariable(BoundRangeVariable node) { VisitWithoutDiagnostics(node.Value); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Need to review this return null; } public override BoundNode? VisitLabel(BoundLabel node) { var result = base.VisitLabel(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) { var expr = node.Expression; VisitRvalue(expr); // If the expression was a MethodGroup, check nullability of receiver. var receiverOpt = (expr as BoundMethodGroup)?.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { var receiverOpt = node.ReceiverOpt; VisitRvalue(receiverOpt); Debug.Assert(!IsConditionalState); var @event = node.Event; if ([email protected]) { @event = (EventSymbol)AsMemberOfType(ResultType.Type, @event); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); SetUpdatedSymbol(node, node.Event, @event); } VisitRvalue(node.Argument); // https://github.com/dotnet/roslyn/issues/31018: Check for delegate mismatch. if (node.Argument.ConstantValue?.IsNull != true && MakeMemberSlot(receiverOpt, @event) is > 0 and var memberSlot) { this.State[memberSlot] = node.IsAddition ? this.State[memberSlot].Meet(ResultType.State) : NullableFlowState.MaybeNull; } SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29969 Review whether this is the correct result return null; } public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) { var result = base.VisitImplicitReceiver(node); SetNotNullResult(node); return result; } public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { var result = base.VisitNoPiaObjectCreationExpression(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectOrDynamicObjectCreation(node, ImmutableArray<BoundExpression>.Empty, ImmutableArray<VisitArgumentResult>.Empty, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) { var result = base.VisitArrayInitialization(node); SetNotNullResult(node); return result; } private void SetUnknownResultNullability(BoundExpression expression) { SetResultType(expression, TypeWithState.Create(expression.Type, default)); } public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { var result = base.VisitStackAllocArrayCreation(node); Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); SetNotNullResult(node); return result; } public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) { return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) { Debug.Assert(!this.IsConditionalState); bool reportedDiagnostic = false; if (receiverOpt != null && this.State.Reachable) { var resultTypeSymbol = resultType.Type; if (resultTypeSymbol is null) { return false; } #if DEBUG Debug.Assert(receiverOpt.Type is null || AreCloseEnough(receiverOpt.Type, resultTypeSymbol)); #endif if (!ReportPossibleNullReceiverIfNeeded(resultTypeSymbol, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) { return reportedDiagnostic; } LearnFromNonNullTest(receiverOpt, ref this.State); } return reportedDiagnostic; } // Returns false if the type wasn't interesting private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) { reportedDiagnostic = false; if (state.MayBeNull()) { bool isValueType = type.IsValueType; if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) { return false; } ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); reportedDiagnostic = true; } return true; } private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) { VisitArgumentConversionAndInboundAssignmentsAndPreConditions( conversionOpt: null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), stateForLambda: default), extensionMethodThisArgument: true); } private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } public override BoundNode? VisitQueryClause(BoundQueryClause node) { var result = base.VisitQueryClause(node); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Implement nullability analysis in LINQ queries return result; } public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) { var result = base.VisitNameOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) { var result = base.VisitNamespaceExpression(node); SetUnknownResultNullability(node); return result; } // https://github.com/dotnet/roslyn/issues/54583 // Better handle the constructor propagation //public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) //{ //} public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // This is only involved with unbound lambdas or when visiting the source of a converted tuple literal var result = base.VisitUnconvertedInterpolatedString(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitStringInsert(BoundStringInsert node) { var result = base.VisitStringInsert(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { var result = base.VisitConvertedStackAllocExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) { var result = TypeWithAnnotations.Create(node.Type); var rValueType = TypeWithState.ForType(node.Type); SetResult(node, rValueType, result); return null; } public override BoundNode? VisitThrowExpression(BoundThrowExpression node) { VisitThrow(node.Expression); SetResultType(node, default); return null; } public override BoundNode? VisitThrowStatement(BoundThrowStatement node) { VisitThrow(node.ExpressionOpt); return null; } private void VisitThrow(BoundExpression? expr) { if (expr != null) { var result = VisitRvalueWithState(expr); // Cases: // null // null! // Other (typed) expression, including suppressed ones if (result.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); } } SetUnreachable(); } public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundExpression expr = node.Expression; if (expr == null) { return null; } var method = (MethodSymbol)CurrentSymbol; TypeWithAnnotations elementType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, RefKind.None, method.ReturnType, errorLocation: null, diagnostics: null); _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); return null; } protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) { TakeIncrementalSnapshot(node); if (node.Locals.Length > 0) { LocalSymbol local = node.Locals[0]; if (local.DeclarationKind == LocalDeclarationKind.CatchVariable) { int slot = GetOrCreateSlot(local); if (slot > 0) this.State[slot] = NullableFlowState.NotNull; } } if (node.ExceptionSourceOpt != null) { VisitWithoutDiagnostics(node.ExceptionSourceOpt); } base.VisitCatchBlock(node, ref finallyState); } public override BoundNode? VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); _ = CheckPossibleNullReceiver(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode? VisitAttribute(BoundAttribute node) { VisitArguments(node, node.ConstructorArguments, ImmutableArray<RefKind>.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); } SetNotNullResult(node); return null; } public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) { var typeWithAnnotations = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetResult(node.Expression, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { SetNotNullResult(node); return null; } [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] private void EnsureAwaitablePlaceholdersInitialized() { _awaitablePlaceholdersOpt ??= PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>.GetInstance(); } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { SetNotNullResult(node); } return null; } public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) { Visit(node.AwaitableInstancePlaceholder); Visit(node.GetAwaiter); return null; } public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { _ = Visit(node.InvokedExpression); Debug.Assert(ResultType is TypeWithState { Type: FunctionPointerTypeSymbol { }, State: NullableFlowState.NotNull }); _ = VisitArguments( node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); var returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); return null; } protected override string Dump(LocalState state) { return state.Dump(_variables); } protected override bool Meet(ref LocalState self, ref LocalState other) { if (!self.Reachable) return false; if (!other.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Meet(in other); } protected override bool Join(ref LocalState self, ref LocalState other) { if (!other.Reachable) return false; if (!self.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Join(in other); } private void Join(ref PossiblyConditionalState other) { var otherIsConditional = other.IsConditionalState; if (otherIsConditional) { Split(); } if (IsConditionalState) { Join(ref StateWhenTrue, ref otherIsConditional ? ref other.StateWhenTrue : ref other.State); Join(ref StateWhenFalse, ref otherIsConditional ? ref other.StateWhenFalse : ref other.State); } else { Debug.Assert(!otherIsConditional); Join(ref State, ref other.State); } } private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { return conditionalState.State.Clone(); } var state = conditionalState.StateWhenTrue.Clone(); Join(ref state, ref conditionalState.StateWhenFalse); return state; } private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { SetState(conditionalState.State); } else { SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); } } internal sealed class LocalStateSnapshot { internal readonly int Id; internal readonly LocalStateSnapshot? Container; internal readonly BitVector State; internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) { Id = id; Container = container; State = state; } } /// <summary> /// A bit array containing the nullability of variables associated with a method scope. If the method is a /// nested function (a lambda or a local function), there is a reference to the corresponding instance for /// the containing method scope. The instances in the chain are associated with a corresponding /// <see cref="Variables"/> chain, and the <see cref="Id"/> field in this type matches <see cref="Variables.Id"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LocalState : ILocalDataFlowState { private sealed class Boxed { internal LocalState Value; internal Boxed(LocalState value) { Value = value; } } internal readonly int Id; private readonly Boxed? _container; // The representation of a state is a bit vector with two bits per slot: // (false, false) => NotNull, (false, true) => MaybeNull, (true, true) => MaybeDefault. // Slot 0 is used to represent whether the state is reachable (true) or not. private BitVector _state; private LocalState(int id, Boxed? container, BitVector state) { Id = id; _container = container; _state = state; } internal static LocalState Create(LocalStateSnapshot snapshot) { var container = snapshot.Container is null ? null : new Boxed(Create(snapshot.Container)); return new LocalState(snapshot.Id, container, snapshot.State.Clone()); } internal LocalStateSnapshot CreateSnapshot() { return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), _state.Clone()); } public bool Reachable => _state[0]; public bool NormalizeToBottom => false; public static LocalState ReachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: true); } public static LocalState UnreachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: false); } private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) { var container = variables.Container is null ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable)); int capacity = reachable ? variables.NextAvailableIndex : 1; return new LocalState(variables.Id, container, CreateBitVector(capacity, reachable)); } public LocalState CreateNestedMethodState(Variables variables) { Debug.Assert(Id == variables.Container!.Id); return new LocalState(variables.Id, container: new Boxed(this), CreateBitVector(capacity: variables.NextAvailableIndex, reachable: true)); } private static BitVector CreateBitVector(int capacity, bool reachable) { if (capacity < 1) capacity = 1; BitVector state = BitVector.Create(capacity * 2); state[0] = reachable; return state; } private int Capacity => _state.Capacity / 2; private void EnsureCapacity(int capacity) { _state.EnsureCapacity(capacity * 2); } public bool HasVariable(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasVariable(id, index); } private bool HasVariable(int id, int index) { if (Id > id) { return _container!.Value.HasValue(id, index); } else { return Id == id; } } public bool HasValue(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasValue(id, index); } private bool HasValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.HasValue(id, index); } else { return index < Capacity; } } public void Normalize(NullableWalker walker, Variables variables) { if (Id != variables.Id) { Debug.Assert(Id < variables.Id); Normalize(walker, variables.Container!); } else { _container?.Value.Normalize(walker, variables.Container!); int start = Capacity; EnsureCapacity(variables.NextAvailableIndex); Populate(walker, start); } } public void PopulateAll(NullableWalker walker) { _container?.Value.PopulateAll(walker); Populate(walker, start: 1); } private void Populate(NullableWalker walker, int start) { int capacity = Capacity; for (int index = start; index < capacity; index++) { int slot = Variables.ConstructSlot(Id, index); SetValue(Id, index, walker.GetDefaultState(ref this, slot)); } } public NullableFlowState this[int slot] { get { (int id, int index) = Variables.DeconstructSlot(slot); return GetValue(id, index); } set { (int id, int index) = Variables.DeconstructSlot(slot); SetValue(id, index, value); } } private NullableFlowState GetValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.GetValue(id, index); } else { if (index < Capacity && this.Reachable) { index *= 2; var result = (_state[index + 1], _state[index]) switch { (false, false) => NullableFlowState.NotNull, (false, true) => NullableFlowState.MaybeNull, (true, false) => throw ExceptionUtilities.UnexpectedValue(index), (true, true) => NullableFlowState.MaybeDefault }; return result; } return NullableFlowState.NotNull; } } private void SetValue(int id, int index, NullableFlowState value) { if (Id != id) { Debug.Assert(Id > id); _container!.Value.SetValue(id, index, value); } else { // No states should be modified in unreachable code, as there is only one unreachable state. if (!this.Reachable) return; index *= 2; _state[index] = (value != NullableFlowState.NotNull); _state[index + 1] = (value == NullableFlowState.MaybeDefault); } } internal void ForEach<TArg>(Action<int, TArg> action, TArg arg) { _container?.Value.ForEach(action, arg); for (int index = 1; index < Capacity; index++) { action(Variables.ConstructSlot(Id, index), arg); } } internal LocalState GetStateForVariables(int id) { var state = this; while (state.Id != id) { state = state._container!.Value; } return state; } /// <summary> /// Produce a duplicate of this flow analysis state. /// </summary> /// <returns></returns> public LocalState Clone() { var container = _container is null ? null : new Boxed(_container.Value.Clone()); return new LocalState(Id, container, _state.Clone()); } public bool Join(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Join(in other._container!.Value)) { result = true; } if (_state.UnionWith(in other._state)) { result = true; } return result; } public bool Meet(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Meet(in other._container!.Value)) { result = true; } if (_state.IntersectWith(in other._state)) { result = true; } return result; } internal string GetDebuggerDisplay() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(" "); int n = Math.Min(Capacity, 8); for (int i = n - 1; i >= 0; i--) builder.Append(_state[i * 2] ? '?' : '!'); return pooledBuilder.ToStringAndFree(); } internal string Dump(Variables variables) { if (!this.Reachable) return "unreachable"; if (Id != variables.Id) return "invalid"; var builder = PooledStringBuilder.GetInstance(); Dump(builder, variables); return builder.ToStringAndFree(); } private void Dump(StringBuilder builder, Variables variables) { _container?.Value.Dump(builder, variables.Container!); for (int index = 1; index < Capacity; index++) { if (getName(Variables.ConstructSlot(Id, index)) is string name) { builder.Append(name); var annotation = GetValue(Id, index) switch { NullableFlowState.MaybeNull => "?", NullableFlowState.MaybeDefault => "??", _ => "!" }; builder.Append(annotation); } } string? getName(int slot) { VariableIdentifier id = variables[slot]; var name = id.Symbol.Name; int containingSlot = id.ContainingSlot; return containingSlot > 0 ? getName(containingSlot) + "." + name : name; } } } internal sealed class LocalFunctionState : AbstractLocalFunctionState { /// <summary> /// Defines the starting state used in the local function body to /// produce diagnostics and determine types. /// </summary> public LocalState StartingState; public LocalFunctionState(LocalState unreachableState) : base(unreachableState.Clone(), unreachableState.Clone()) { StartingState = unreachableState; } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) { var variables = (symbol.ContainingSymbol is MethodSymbol containingMethod ? _variables.GetVariablesForMethodScope(containingMethod) : null) ?? _variables.GetRootScope(); return new LocalFunctionState(LocalState.UnreachableState(variables)); } private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> { public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) { return x.info.Equals(y.info) && Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); } public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) { return obj.GetHashCode(); } } private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> { internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); private ExpressionAndSymbolEqualityComparer() { } public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) { RoslynDebug.Assert(x.symbol is object); RoslynDebug.Assert(y.symbol is object); // We specifically use reference equality for the symbols here because the BoundNode should be immutable. // We should be storing and retrieving the exact same instance of the symbol, not just an "equivalent" // symbol. return x.expr == y.expr && (object)x.symbol == y.symbol; } public int GetHashCode((BoundNode? expr, Symbol symbol) obj) { RoslynDebug.Assert(obj.symbol is object); return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Nullability flow analysis. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed partial class NullableWalker : LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState> { /// <summary> /// Used to copy variable slots and types from the NullableWalker for the containing method /// or lambda to the NullableWalker created for a nested lambda or local function. /// </summary> internal sealed class VariableState { // Consider referencing the Variables instance directly from the original NullableWalker // rather than cloning. (Items are added to the collections but never replaced so the // collections are lazily populated but otherwise immutable. We'd probably want a // clone when analyzing from speculative semantic model though.) internal readonly VariablesSnapshot Variables; // The nullable state of all variables captured at the point where the function or lambda appeared. internal readonly LocalStateSnapshot VariableNullableStates; internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) { Variables = variables; VariableNullableStates = variableNullableStates; } } /// <summary> /// Data recorded for a particular analysis run. /// </summary> internal readonly struct Data { /// <summary> /// Number of entries tracked during analysis. /// </summary> internal readonly int TrackedEntries; /// <summary> /// True if analysis was required; false if analysis was optional and results dropped. /// </summary> internal readonly bool RequiredAnalysis; internal Data(int trackedEntries, bool requiredAnalysis) { TrackedEntries = trackedEntries; RequiredAnalysis = requiredAnalysis; } } /// <summary> /// Represents the result of visiting an expression. /// Contains a result type which tells us whether the expression may be null, /// and an l-value type which tells us whether we can assign null to the expression. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct VisitResult { public readonly TypeWithState RValueType; public readonly TypeWithAnnotations LValueType; public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) { RValueType = rValueType; LValueType = lValueType; // https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true //Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) || // RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions)); } public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) { RValueType = TypeWithState.Create(type, state); LValueType = TypeWithAnnotations.Create(type, annotation); Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything)); } internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}"; } /// <summary> /// Represents the result of visiting an argument expression. /// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/> /// for reanalyzing a lambda. /// </summary> [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] private readonly struct VisitArgumentResult { public readonly VisitResult VisitResult; public readonly Optional<LocalState> StateForLambda; public TypeWithState RValueType => VisitResult.RValueType; public TypeWithAnnotations LValueType => VisitResult.LValueType; public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda) { VisitResult = visitResult; StateForLambda = stateForLambda; } } private Variables _variables; /// <summary> /// Binder for symbol being analyzed. /// </summary> private readonly Binder _binder; /// <summary> /// Conversions with nullability and unknown matching any. /// </summary> private readonly Conversions _conversions; /// <summary> /// 'true' if non-nullable member warnings should be issued at return points. /// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type. /// </summary> private readonly bool _useConstructorExitWarnings; /// <summary> /// If true, the parameter types and nullability from _delegateInvokeMethod is used for /// initial parameter state. If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeParameterTypes; /// <summary> /// If true, the return type and nullability from _delegateInvokeMethod is used. /// If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeReturnType; /// <summary> /// Method signature used for return or parameter types. Distinct from CurrentSymbol signature /// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer. /// </summary> private MethodSymbol? _delegateInvokeMethod; /// <summary> /// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer. /// </summary> private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; /// <summary> /// Invalid type, used only to catch Visit methods that do not set /// _result.Type. See VisitExpressionWithoutStackGuard. /// </summary> private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull); /// <summary> /// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the /// compiler. /// </summary> private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt; /// <summary> /// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of /// this walker. /// </summary> private readonly SnapshotManager.Builder? _snapshotBuilderOpt; // https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported private bool _disableNullabilityAnalysis; /// <summary> /// State of method group receivers, used later when analyzing the conversion to a delegate. /// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.) /// </summary> private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt; /// <summary> /// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls. /// </summary> private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt; /// <summary> /// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This /// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These /// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value. /// </summary> private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion => _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.GetInstance(); /// <summary> /// True if we're analyzing speculative code. This turns off some initialization steps /// that would otherwise be taken. /// </summary> private readonly bool _isSpeculative; /// <summary> /// True if this walker was created using an initial state. /// </summary> private readonly bool _hasInitialState; #if DEBUG /// <summary> /// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>. /// </summary> private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization, BoundKind.ObjectInitializerExpression, BoundKind.CollectionInitializerExpression, BoundKind.DynamicCollectionElementInitializer); #endif /// <summary> /// The result and l-value type of the last visited expression. /// </summary> private VisitResult _visitResult; /// <summary> /// The visit result of the receiver for the current conditional access. /// /// For example: A conditional invocation uses a placeholder as a receiver. By storing the /// visit result from the actual receiver ahead of time, we can give this placeholder a correct result. /// </summary> private VisitResult _currentConditionalReceiverVisitResult; /// <summary> /// The result type represents the state of the last visited expression. /// </summary> private TypeWithState ResultType { get => _visitResult.RValueType; } private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) { SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability); } /// <summary> /// Force the inference of the LValueResultType from ResultType. /// </summary> private void UseRvalueOnly(BoundExpression? expression) { SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false); } private TypeWithAnnotations LvalueResultType { get => _visitResult.LValueType; } private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) { SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type); } /// <summary> /// Force the inference of the ResultType from LValueResultType. /// </summary> private void UseLvalueOnly(BoundExpression? expression) { SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true); } private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) { _visitResult = new VisitResult(resultType, lvalueType); if (updateAnalyzedNullability) { SetAnalyzedNullability(expression, _visitResult, isLvalue); } } private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable(); /// <summary> /// Sets the analyzed nullability of the expression to be the given result. /// </summary> private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) { if (expr == null || _disableNullabilityAnalysis) return; #if DEBUG // https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't // changing the observable results of GetTypeInfo beyond nullability information. //Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type), // $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}"); #endif if (_analyzedNullabilityMapOpt != null) { // https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions #if false if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing)) { if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable))) { switch (isLvalue) { case true: Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(), $"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}"); break; case false: Debug.Assert(existing.Info.FlowState == result.RValueType.State, $"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}"); break; case null: Debug.Assert(existing.Info.Equals((NullabilityInfo)result), $"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})"); break; } } } #endif _analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()), // https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely // with the existing type expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type); } } /// <summary> /// Placeholder locals, e.g. for objects being constructed. /// </summary> private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt; /// <summary> /// For methods with annotations, we'll need to visit the arguments twice. /// Once for diagnostics and once for result state (but disabling diagnostics). /// </summary> private bool _disableDiagnostics = false; /// <summary> /// Whether we are going to read the currently visited expression. /// </summary> private bool _expressionIsRead = true; /// <summary> /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when /// it's encountered. /// </summary> private int _lastConditionalAccessSlot = -1; private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; protected override void Free() { _nestedFunctionVariables?.Free(); _awaitablePlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 }); _conditionalInfoForConversionOpt?.Free(); base.Free(); } private NullableWalker( CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object); _variables = variables ?? Variables.Create(symbol); _binder = binder; _conversions = (Conversions)conversions.WithNullability(true); _useConstructorExitWarnings = useConstructorExitWarnings; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; _delegateInvokeMethod = delegateInvokeMethodOpt; _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; _returnTypesOpt = returnTypesOpt; _snapshotBuilderOpt = snapshotBuilderOpt; _isSpeculative = isSpeculative; _hasInitialState = variables is { }; } public string GetDebuggerDisplay() { if (this.IsConditionalState) { return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}"; } else { return $"{{{GetType().Name} {Dump(State)}{"}"}"; } } // For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; protected override void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth && compilation.NullableAnalysisData is { MaxRecursionDepth: var depth } && depth > 0 && recursionDepth > depth) { throw new InsufficientExecutionStackException(); } base.EnsureSufficientExecutionStack(recursionDepth); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) { return _variables.TryGetValue(identifier, out slot); } protected override int AddVariable(VariableIdentifier identifier) { return _variables.Add(identifier); } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { if (_returnTypesOpt != null) { _returnTypesOpt.Clear(); } this.Diagnostics.Clear(); this.regionPlace = RegionPlace.Before; if (!_isSpeculative) { ParameterSymbol methodThisParameter = MethodThisParameter; EnterParameters(); // assign parameters if (methodThisParameter is object) { EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); } makeNotNullMembersMaybeNull(); // We need to create a snapshot even of the first node, because we want to have the state of the initial parameters. _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); } ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion); if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings) { EnforceDoesNotReturn(syntaxOpt: null); enforceMemberNotNull(syntaxOpt: null, this.State); enforceNotNull(null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { enforceNotNull(returnStatement.Syntax, pendingReturn.State); enforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } } return pendingReturns; void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } var method = _symbol as MethodSymbol; if (method is object) { if (method.IsConstructor()) { Debug.Assert(_useConstructorExitWarnings); var thisSlot = 0; if (method.RequiresInstanceReceiver) { method.TryGetThisParameter(out var thisParameter); Debug.Assert(thisParameter is object); thisSlot = GetOrCreateSlot(thisParameter); } // https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault(); foreach (var member in method.ContainingType.GetMembersUnordered()) { checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation); } } else { do { foreach (var memberName in method.NotNullMembers) { enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName); } method = method.OverriddenMethod; } while (method != null); } } } void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation) { var isStatic = !constructor.RequiresInstanceReceiver(); if (member.IsStatic != isStatic) { return; } // This is not required for correctness, but in the case where the member has // an initializer, we know we've assigned to the member and // have given any applicable warnings about a bad value going in. // Therefore we skip this check when the member has an initializer to reduce noise. if (HasInitializer(member)) { return; } TypeWithAnnotations fieldType; FieldSymbol? field; Symbol symbol; switch (member) { case FieldSymbol f: fieldType = f.TypeWithAnnotations; field = f; symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f; break; case EventSymbol e: fieldType = e.TypeWithAnnotations; field = e.AssociatedField; symbol = e; if (field is null) { return; } break; default: return; } if (field.IsConst) { return; } if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType()) { return; } var annotations = symbol.GetFlowAnalysisAnnotations(); if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { // We assume that if a member has AllowNull then the user // does not care that we exit at a point where the member might be null. return; } fieldType = ApplyUnconditionalAnnotations(fieldType, annotations); if (!fieldType.NullableAnnotation.IsNotAnnotated()) { return; } var slot = GetOrCreateSlot(symbol, thisSlot); if (slot < 0) { return; } var memberState = state[slot]; var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0 ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'? { Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name); } } void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) { foreach (var member in method.ContainingType.GetMembers(memberName)) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name); } } } void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } if (_symbol is MethodSymbol method) { foreach (var memberName in method.NotNullWhenTrueMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); } foreach (var memberName in method.NotNullWhenFalseMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); } } void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState) { foreach (var member in members) { // For non-constant values, only complain if we were able to analyze a difference for this member between two branches if (memberHasBadState(member, state) != memberHasBadState(member, otherState)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) { if (_symbol is MethodSymbol method) { var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers; foreach (var memberName in notNullMembers) { foreach (var member in method.ContainingType.GetMembers(memberName)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } } void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false"); } } bool memberHasBadState(Symbol member, LocalState state) { switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { var parameterState = state[memberSlot]; return !parameterState.IsNotNull(); } else { return false; } case SymbolKind.Event: case SymbolKind.Method: break; } return false; } void makeNotNullMembersMaybeNull() { if (_symbol is MethodSymbol method) { if (method.IsConstructor()) { if (needsDefaultInitialStateForMembers()) { foreach (var member in method.ContainingType.GetMembersUnordered()) { if (member.IsStatic != method.IsStatic) { continue; } var memberToInitialize = member; switch (member) { case PropertySymbol: // skip any manually implemented properties. continue; case FieldSymbol { IsConst: true }: continue; case FieldSymbol { AssociatedSymbol: PropertySymbol prop }: // this is a property where assigning 'default' causes us to simply update // the state to the output state of the property // thus we skip setting an initial state for it here if (IsPropertyOutputMoreStrictThanInput(prop)) { continue; } // We want to initialize auto-property state to the default state, but not computed properties. memberToInitialize = prop; break; default: break; } var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize); if (memberSlot > 0) { var type = memberToInitialize.GetTypeOrReturnType(); if (!type.NullableAnnotation.IsOblivious()) { this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } } } else { do { makeMembersMaybeNull(method, method.NotNullMembers); makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); method = method.OverriddenMethod; } while (method != null); } } bool needsDefaultInitialStateForMembers() { if (_hasInitialState) { return false; } // We don't use a default initial state for value type instance constructors without `: this()` because // any usages of uninitialized fields will get definite assignment errors anyway. if (!method.HasThisConstructorInitializer(out _) && (!method.ContainingType.IsValueType || method.IsStatic)) { return true; } return method.IncludeFieldInitializersInBody(); } } void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members) { foreach (var memberName in members) { makeMemberMaybeNull(method, memberName); } } void makeMemberMaybeNull(MethodSymbol method, string memberName) { var type = method.ContainingType; foreach (var member in type.GetMembers(memberName)) { if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { this.State[memberSlot] = NullableFlowState.MaybeNull; } } } void enforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { var parameters = this.MethodParameters; if (!parameters.IsEmpty) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } foreach (var parameter in parameters) { // For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot]) { reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue); reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { // example: return (bool)true; enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } void reportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) { if (parameterHasBadConditionalState(parameter, sense, stateWhen)) { // Parameter '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); } } void enforceNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } foreach (var parameter in this.MethodParameters) { var slot = GetOrCreateSlot(parameter); if (slot <= 0) { continue; } var annotations = parameter.FlowAnalysisAnnotations; var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; var parameterState = state[slot]; if (hasNotNull && parameterState.MayBeNull()) { // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen) { var refKind = parameter.RefKind; if (refKind != RefKind.Out && refKind != RefKind.Ref) { return false; } var slot = GetOrCreateSlot(parameter); if (slot > 0) { var parameterState = stateWhen[slot]; // On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning. // We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen. FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations; if (sense) { bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; return (hasNotNullWhenTrue && parameterState.MayBeNull()) || (hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } else { bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; return (hasNotNullWhenFalse && parameterState.MayBeNull()) || (hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } } return false; } int getSlotForFieldOrPropertyOrEvent(Symbol member) { if (member.Kind != SymbolKind.Field && member.Kind != SymbolKind.Property && member.Kind != SymbolKind.Event) { return -1; } int containingSlot = 0; if (!member.IsStatic) { if (MethodThisParameter is null) { return -1; } containingSlot = GetOrCreateSlot(MethodThisParameter); if (containingSlot < 0) { return -1; } Debug.Assert(containingSlot > 0); } return GetOrCreateSlot(member, containingSlot); } } private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) { if (inputParamNames.IsEmpty || outputState.IsNotNull()) { return; } foreach (var inputParam in parameters) { if (inputParamNames.Contains(inputParam.Name) && GetOrCreateSlot(inputParam) is > 0 and int inputSlot && state[inputSlot].IsNotNull()) { var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); if (outputParam is object) { // Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name); } else if (CurrentSymbol is MethodSymbol { IsAsync: false }) { // Return value must be non-null because parameter '{0}' is non-null. Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name); } break; } } } private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) { // DoesNotReturn is only supported in member methods if (CurrentSymbol is MethodSymbol { ContainingSymbol: TypeSymbol _ } method && ((method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) && this.IsReachable()) { // A method marked [DoesNotReturn] should not return. ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation()); } } /// <summary> /// Analyzes a method body if settings indicate we should. /// </summary> internal static void AnalyzeIfNeeded( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState) { if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) { if (compilation.IsNullableAnalysisEnabledAlways) { // Once we address https://github.com/dotnet/roslyn/issues/46579 we should also always pass `getFinalNullableState: true` in debug mode. // We will likely always need to write a 'null' out for the out parameter in this code path, though, because // we don't want to introduce behavior differences between debug and release builds Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: false, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) { finalNullableState = null; return; } Debug.Assert(node.SyntaxTree is object); var binder = method is SynthesizedSimpleProgramEntryPointSymbol entryPoint ? entryPoint.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax); var conversions = binder.Conversions; Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: initialNullableState, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. Only used for semantic model and debug verification. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { var unusedDiagnostics = DiagnosticBag.GetInstance(); Binder.ProcessedFieldInitializers initializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref initializers); NullableWalker.AnalyzeIfNeeded( compilation, method, InitializerRewriter.RewriteConstructor(initializers.BoundInitializers, method), unusedDiagnostics, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out var afterInitializersState); unusedDiagnostics.Free(); return afterInitializersState; } return null; } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information. This method is only /// used when nullable is explicitly enabled for all methods but disabled otherwise to verify that /// correct semantic information is being recorded for all bound nodes. The results are thrown away. /// </summary> internal static void AnalyzeWithoutRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) { _ = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState: GetAfterInitializersState(compilation, symbol), diagnostics, createSnapshots, requiresAnalysis: false); } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information, and returns an /// updated BoundNode with the information populated. /// </summary> internal static BoundNode AnalyzeAndRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> analyzedNullabilitiesMap; (snapshotManager, analyzedNullabilitiesMap) = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); return Rewrite(analyzedNullabilitiesMap, snapshotManager, node, ref remappedSymbols); } private static (SnapshotManager?, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>) AnalyzeWithSemanticInfo( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); // Attributes don't have a symbol, which is what SnapshotBuilder uses as an index for maintaining global state. // Until we have a workaround for this, disable snapshots for null symbols. // https://github.com/dotnet/roslyn/issues/36066 var snapshotBuilder = createSnapshots && symbol != null ? new SnapshotManager.Builder() : null; Analyze( compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState, analyzedNullabilities, snapshotBuilder, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); var snapshotManager = snapshotBuilder?.ToManagerAndFree(); #if DEBUG // https://github.com/dotnet/roslyn/issues/34993 Enable for all calls if (isNullableAnalysisEnabledAnywhere(compilation)) { DebugVerifier.Verify(analyzedNullabilitiesMap, snapshotManager, node); } static bool isNullableAnalysisEnabledAnywhere(CSharpCompilation compilation) { if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { return true; } return compilation.SyntaxTrees.Any(tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new Text.TextSpan(0, tree.Length)) == true); } #endif return (snapshotManager, analyzedNullabilitiesMap); } internal static BoundNode AnalyzeAndRewriteSpeculation( int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); var newSnapshotBuilder = new SnapshotManager.Builder(); var (variables, localState) = originalSnapshots.GetSnapshot(position); var symbol = variables.Symbol; var walker = new NullableWalker( binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, binder.Conversions, Variables.Create(variables), returnTypesOpt: null, analyzedNullabilities, newSnapshotBuilder, isSpeculative: true); try { Analyze(walker, symbol, diagnostics: null, LocalState.Create(localState), snapshotBuilderOpt: newSnapshotBuilder); } finally { walker.Free(); } var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); newSnapshots = newSnapshotBuilder.ToManagerAndFree(); #if DEBUG DebugVerifier.Verify(analyzedNullabilitiesMap, newSnapshots, node); #endif return Rewrite(analyzedNullabilitiesMap, newSnapshots, node, ref remappedSymbols); } private static BoundNode Rewrite(ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var remappedSymbolsBuilder = ImmutableDictionary.CreateBuilder<Symbol, Symbol>(Symbols.SymbolEqualityComparer.ConsiderEverything, Symbols.SymbolEqualityComparer.ConsiderEverything); if (remappedSymbols is object) { // When we're rewriting for the speculative model, there will be a set of originally-mapped symbols, and we need to // use them in addition to any symbols found during this pass of the walker. remappedSymbolsBuilder.AddRange(remappedSymbols); } var rewriter = new NullabilityRewriter(updatedNullabilities, snapshotManager, remappedSymbolsBuilder); var rewrittenNode = rewriter.Visit(node); remappedSymbols = remappedSymbolsBuilder.ToImmutable(); return rewrittenNode; } private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) { return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); } /// <summary> /// Returns true if the nullable analysis is needed for the region represented by <paramref name="syntaxNode"/>. /// The syntax node is used to determine the overall nullable context for the region. /// </summary> internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) { return HasRequiredLanguageVersion(compilation) && (compilation.IsNullableAnalysisEnabledIn(syntaxNode) || compilation.IsNullableAnalysisEnabledAlways); } /// <summary>Analyzes a node in a "one-off" context, such as for attributes or parameter default values.</summary> /// <remarks><paramref name="syntax"/> is the syntax span used to determine the overall nullable context.</remarks> internal static void AnalyzeIfNeeded( Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) { bool requiresAnalysis = true; var compilation = binder.Compilation; if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(syntax)) { if (!compilation.IsNullableAnalysisEnabledAlways) { return; } diagnostics = new DiagnosticBag(); requiresAnalysis = false; } Analyze( compilation, symbol: null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); } internal static void Analyze( CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) { var symbol = lambda.Symbol; var variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); var walker = new NullableWalker( compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: useDelegateInvokeParameterTypes, useDelegateInvokeReturnType: useDelegateInvokeReturnType, delegateInvokeMethodOpt: delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, returnTypesOpt, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); try { var localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); Analyze(walker, symbol, diagnostics, localState, snapshotBuilderOpt: null); } finally { walker.Free(); } } private static void Analyze( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { Debug.Assert(diagnostics != null); var walker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, initialState is null ? null : Variables.Create(initialState.Variables), returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); finalNullableState = null; try { Analyze(walker, symbol, diagnostics, initialState is null ? (Optional<LocalState>)default : LocalState.Create(initialState.VariableNullableStates), snapshotBuilderOpt, requiresAnalysis); if (getFinalNullableState) { Debug.Assert(!walker.IsConditionalState); finalNullableState = GetVariableState(walker._variables, walker.State); } } finally { walker.Free(); } } private static void Analyze( NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional<LocalState> initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) { Debug.Assert(snapshotBuilderOpt is null || symbol is object); var previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol!) ?? -1; try { bool badRegion = false; ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion, initialState); diagnostics?.AddRange(walker.Diagnostics); Debug.Assert(!badRegion); } catch (CancelledByStackGuardException ex) when (diagnostics != null) { ex.AddAnError(diagnostics); } finally { snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); } walker.RecordNullableAnalysisData(symbol, requiresAnalysis); } private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) { if (compilation.NullableAnalysisData?.Data is { } state) { var key = (object?)symbol ?? methodMainNode.Syntax; if (state.TryGetValue(key, out var result)) { Debug.Assert(result.RequiredAnalysis == requiredAnalysis); } else { state.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); } } } private SharedWalkerState SaveSharedState() { return new SharedWalkerState(_variables.CreateSnapshot()); } private void TakeIncrementalSnapshot(BoundNode? node) { Debug.Assert(!IsConditionalState); _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); } private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) { if (_snapshotBuilderOpt is null) { return; } var lambdaIsExactMatch = false; if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) { if (!AreLambdaAndNewDelegateSimilar(l, n)) { return; } lambdaIsExactMatch = updatedSymbol.Equals(boundLambda.Type!.GetDelegateType(), TypeCompareKind.ConsiderEverything); } #if DEBUG Debug.Assert(node is object); Debug.Assert(AreCloseEnough(originalSymbol, updatedSymbol), $"Attempting to set {node.Syntax} from {originalSymbol.ToDisplayString()} to {updatedSymbol.ToDisplayString()}"); #endif if (lambdaIsExactMatch || Symbol.Equals(originalSymbol, updatedSymbol, TypeCompareKind.ConsiderEverything)) { // If the symbol is reset, remove the updated symbol so we don't needlessly update the // bound node later on. We do this unconditionally, as Remove will just return false // if the key wasn't in the dictionary. _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); } else { _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); } } protected override void Normalize(ref LocalState state) { if (!state.Reachable) return; state.Normalize(this, _variables); } private NullableFlowState GetDefaultState(ref LocalState state, int slot) { Debug.Assert(slot > 0); if (!state.Reachable) return NullableFlowState.NotNull; var variable = _variables[slot]; var symbol = variable.Symbol; switch (symbol.Kind) { case SymbolKind.Local: { var local = (LocalSymbol)symbol; if (!_variables.TryGetType(local, out TypeWithAnnotations localType)) { localType = local.TypeWithAnnotations; } return localType.ToTypeWithState().State; } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (!_variables.TryGetType(parameter, out TypeWithAnnotations parameterType)) { parameterType = parameter.TypeWithAnnotations; } return GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; } case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return GetDefaultState(symbol); case SymbolKind.ErrorType: return NullableFlowState.NotNull; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) { receiver = null; member = null; switch (expr.Kind) { case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; member = fieldSymbol; if (fieldSymbol.IsFixedSizeBuffer) { return false; } if (fieldSymbol.IsStatic) { return true; } receiver = fieldAccess.ReceiverOpt; break; } case BoundKind.EventAccess: { var eventAccess = (BoundEventAccess)expr; var eventSymbol = eventAccess.EventSymbol; // https://github.com/dotnet/roslyn/issues/29901 Use AssociatedField for field-like events? member = eventSymbol; if (eventSymbol.IsStatic) { return true; } receiver = eventAccess.ReceiverOpt; break; } case BoundKind.PropertyAccess: { var propAccess = (BoundPropertyAccess)expr; var propSymbol = propAccess.PropertySymbol; member = propSymbol; if (propSymbol.IsStatic) { return true; } receiver = propAccess.ReceiverOpt; break; } } Debug.Assert(member?.RequiresInstanceReceiver() ?? true); return member is object && receiver is object && receiver.Kind != BoundKind.TypeExpression && receiver.Type is object; } protected override int MakeSlot(BoundExpression node) { int result = makeSlot(node); #if DEBUG if (result != -1) { // Check that the slot represents a value of an equivalent type to the node TypeSymbol slotType = NominalSlotType(result); TypeSymbol? nodeType = node.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = this.compilation.Conversions; Debug.Assert(node.HasErrors || nodeType!.IsErrorType() || conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(slotType, nodeType, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(slotType, nodeType, ref discardedUseSiteInfo)); } #endif return result; int makeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: { var method = getTopLevelMethod(_symbol as MethodSymbol); var thisParameter = method?.ThisParameter; return thisParameter is object ? GetOrCreateSlot(thisParameter) : -1; } case BoundKind.Conversion: { int slot = getPlaceholderSlot(node); if (slot > 0) { return slot; } var conv = (BoundConversion)node; switch (conv.Conversion.Kind) { case ConversionKind.ExplicitNullable: { var operand = conv.Operand; var operandType = operand.Type; var convertedType = conv.Type; if (AreNullableAndUnderlyingTypes(operandType, convertedType, out _)) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. // For instance, in the following, when evaluating `((A)a).B` we need to recognize // the nullability of `(A)a` (not nullable) and the slot (the slot for `a.Value`). // struct A { B? B; } // struct B { } // if (a?.B != null) _ = ((A)a).B.Value; // no warning int containingSlot = MakeSlot(operand); return containingSlot < 0 ? -1 : GetNullableOfTValueSlot(operandType, containingSlot, out _); } } break; case ConversionKind.Identity: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.Boxing: // No need to create a slot for the boxed value (in the Boxing case) since assignment already // clones slots and there is not another scenario where creating a slot is observable. return MakeSlot(conv.Operand); } } break; case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.ObjectCreationExpression: case BoundKind.DynamicObjectCreationExpression: case BoundKind.AnonymousObjectCreationExpression: case BoundKind.NewT: case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return getPlaceholderSlot(node); case BoundKind.ConditionalAccess: return getPlaceholderSlot(node); case BoundKind.ConditionalReceiver: return _lastConditionalAccessSlot; default: { int slot = getPlaceholderSlot(node); return (slot > 0) ? slot : base.MakeSlot(node); } } return -1; } int getPlaceholderSlot(BoundExpression expr) { if (_placeholderLocalsOpt != null && _placeholderLocalsOpt.TryGetValue(expr, out var placeholder)) { return GetOrCreateSlot(placeholder); } return -1; } static MethodSymbol? getTopLevelMethod(MethodSymbol? method) { while (method is object) { var container = method.ContainingSymbol; if (container.Kind == SymbolKind.NamedType) { return method; } method = container as MethodSymbol; } return null; } } protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) return -1; return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); } private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode { if (nodes.IsDefault) { return; } foreach (var node in nodes) { Visit(node); Unsplit(); } } private void VisitWithoutDiagnostics(BoundNode? node) { var previousDiagnostics = _disableDiagnostics; _disableDiagnostics = true; Visit(node); _disableDiagnostics = previousDiagnostics; } protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) { Visit(node); VisitRvalueEpilogue(node); } /// <summary> /// The contents of this method, particularly <see cref="UseRvalueOnly"/>, are problematic when /// inlined. The methods themselves are small but they end up allocating significantly larger /// frames due to the use of biggish value types within them. The <see cref="VisitRvalue"/> method /// is used on a hot path for fluent calls and this size change is enough that it causes us /// to exceed our thresholds in EndToEndTests.OverflowOnFluentCall. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void VisitRvalueEpilogue(BoundExpression? node) { Unsplit(); UseRvalueOnly(node); // drop lvalue part } private TypeWithState VisitRvalueWithState(BoundExpression? node) { VisitRvalue(node); return ResultType; } private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) { VisitLValue(node); Unsplit(); return LvalueResultType; } private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) { return typeOpt ?? (object)"<null>"; } private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) { return parameterOpt is null ? (object)"" : new FormattedSymbol(parameterOpt, SymbolDisplayFormat.ShortFormat); } private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) { var containingSymbol = parameterOpt?.ContainingSymbol; return containingSymbol is null ? (object)"" : new FormattedSymbol(containingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat); } private enum AssignmentKind { Assignment, Return, Argument, ForEachIterationVariable } /// <summary> /// Should we warn for assigning this state into this type? /// /// This should often be checked together with <seealso cref="IsDisallowedNullAssignment(TypeWithState, FlowAnalysisAnnotations)"/> /// It catches putting a `null` into a `[DisallowNull]int?` for example, which cannot simply be represented as a non-nullable target type. /// </summary> private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) { if (!type.HasType || type.Type.IsValueType) { return false; } switch (type.NullableAnnotation) { case NullableAnnotation.Oblivious: case NullableAnnotation.Annotated: return false; } switch (state) { case NullableFlowState.NotNull: return false; case NullableFlowState.MaybeNull: if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && !(type.Type is TypeParameterSymbol { IsNotNullable: true })) { return false; } break; } return true; } /// <summary> /// Reports top-level nullability problem in assignment. /// Any conversion of the value should have been applied. /// </summary> private void ReportNullableAssignmentIfNecessary( BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) { // Callers should apply any conversions before calling this method // (see https://github.com/dotnet/roslyn/issues/39867). if (targetType.HasType && !targetType.Type.Equals(valueType.Type, TypeCompareKind.AllIgnoreOptions)) { return; } if (value == null || // This prevents us from giving undesired warnings for synthesized arguments for optional parameters, // but allows us to give warnings for synthesized assignments to record properties and for parameter default values at the declaration site. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument) || !ShouldReportNullableAssignment(targetType, valueType.State)) { return; } location ??= value.Syntax.GetLocation(); var unwrappedValue = SkipReferenceConversions(value); if (unwrappedValue.IsSuppressed) { return; } if (value.ConstantValue?.IsNull == true && !useLegacyWarnings) { // Report warning converting null literal to non-nullable reference type. // target (e.g.: `object F() => null;` or calling `void F(object y)` with `F(null)`). ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); } else if (assignmentKind == AssignmentKind.Argument) { ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); LearnFromNonNullTest(value, ref State); } else if (useLegacyWarnings) { if (isMaybeDefaultValue(valueType) && !allowUnconstrainedTypeParameterAnnotations(compilation)) { // No W warning reported assigning or casting [MaybeNull]T value to T // because there is no syntax for declaring the target type as [MaybeNull]T. return; } ReportNonSafetyDiagnostic(location); } else { ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); } static bool isMaybeDefaultValue(TypeWithState valueType) { return valueType.Type?.TypeKind == TypeKind.TypeParameter && valueType.State == NullableFlowState.MaybeDefault; } static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); return requiredVersion <= compilation.LanguageVersion; } } internal static bool AreParameterAnnotationsCompatible( RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) { // We've already checked types and annotations, let's check nullability attributes as well // Return value is treated as an `out` parameter (or `ref` if it is a `ref` return) if (refKind == RefKind.Ref) { // ref variables are invariant return AreParameterAnnotationsCompatible(RefKind.None, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true) && AreParameterAnnotationsCompatible(RefKind.Out, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); } if (refKind == RefKind.None || refKind == RefKind.In) { // pre-condition attributes // Check whether we can assign a value from overridden parameter to overriding var valueState = GetParameterState(overriddenType, overriddenAnnotations); if (isBadAssignment(valueState, overridingType, overridingAnnotations)) { return false; } // unconditional post-condition attributes on inputs bool overridingHasNotNull = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; bool overriddenHasNotNull = (overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; if (overriddenHasNotNull && !overridingHasNotNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise not to return if parameter is null) return false; } bool overridingHasMaybeNull = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; bool overriddenHasMaybeNull = (overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; if (overriddenHasMaybeNull && !overridingHasMaybeNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise to only return if parameter is null) return false; } } if (refKind == RefKind.Out) { // post-condition attributes (`Maybe/NotNull` and `Maybe/NotNullWhen`) if (!canAssignOutputValueWhen(true) || !canAssignOutputValueWhen(false)) { return false; } } return true; bool canAssignOutputValueWhen(bool sense) { var valueWhen = ApplyUnconditionalAnnotations( overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)); var destAnnotationsWhen = ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)); if (isBadAssignment(valueWhen, overriddenType, destAnnotationsWhen)) { // Can't assign value from overriding to overridden in 'sense' case return false; } return true; } static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) { if (ShouldReportNullableAssignment( ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) { return true; } if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) { return true; } return false; } // Convert both conditional annotations to unconditional ones or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) { if (sense) { var unconditionalAnnotationWhenTrue = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenTrue, FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); } var unconditionalAnnotationWhenFalse = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenFalse, FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); } // Convert Maybe/NotNullWhen into Maybe/NotNull or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) { if ((annotations & conditionalAnnotation) != 0) { return annotations | replacementAnnotation; } return annotations & ~replacementAnnotation; } } private static bool IsDefaultValue(BoundExpression expr) { switch (expr.Kind) { case BoundKind.Conversion: { var conversion = (BoundConversion)expr; var conversionKind = conversion.Conversion.Kind; return (conversionKind == ConversionKind.DefaultLiteral || conversionKind == ConversionKind.NullLiteral) && IsDefaultValue(conversion.Operand); } case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; default: return false; } } private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); } private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); } /// <summary> /// Update tracked value on assignment. /// </summary> private void TrackNullableStateForAssignment( BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) { Debug.Assert(!IsConditionalState); if (this.State.Reachable) { if (!targetType.HasType) { return; } if (targetSlot <= 0 || targetSlot == valueSlot) { return; } if (!this.State.HasValue(targetSlot)) Normalize(ref this.State); var newState = valueType.State; SetStateAndTrackForFinally(ref this.State, targetSlot, newState); InheritDefaultState(targetType.Type, targetSlot); // https://github.com/dotnet/roslyn/issues/33428: Can the areEquivalentTypes check be removed // if InheritNullableStateOfMember asserts the member is valid for target and value? if (areEquivalentTypes(targetType, valueType)) { if (targetType.Type.IsReferenceType || targetType.TypeKind == TypeKind.TypeParameter || targetType.IsNullableType()) { if (valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot: targetSlot); } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) { InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, isDefaultValue: !(valueOpt is null) && IsDefaultValue(valueOpt), skipSlot: targetSlot); } } } static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) => target.Type.Equals(assignedValue.Type, TypeCompareKind.AllIgnoreOptions); } private void ReportNonSafetyDiagnostic(Location location) { ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); } private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) { ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); } private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) { Debug.Assert(ErrorFacts.NullableWarnings.Contains(MessageProvider.Instance.GetIdForErrorCode((int)errorCode))); if (IsReachable() && !_disableDiagnostics) { Diagnostics.Add(errorCode, location, arguments); } } private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) { Debug.Assert(targetSlot > 0); Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType)); if (skipSlot < 0) { skipSlot = targetSlot; } if (!isDefaultValue && valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); } else { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType)) { InheritNullableStateOfMember(targetSlot, valueSlot, field, isDefaultValue: isDefaultValue, skipSlot); } } } private bool IsSlotMember(int slot, Symbol possibleMember) { TypeSymbol possibleBase = possibleMember.ContainingType; TypeSymbol possibleDerived = NominalSlotType(slot); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = _conversions.WithNullability(false); return conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } // 'skipSlot' is the original target slot that should be skipped in case of cycles. private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) { Debug.Assert(targetContainerSlot > 0); Debug.Assert(skipSlot > 0); // Ensure member is valid for target and value. if (!IsSlotMember(targetContainerSlot, member)) return; TypeWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType(); if (fieldOrPropertyType.Type.IsReferenceType || fieldOrPropertyType.TypeKind == TypeKind.TypeParameter || fieldOrPropertyType.IsNullableType()) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { NullableFlowState value = isDefaultValue ? NullableFlowState.MaybeNull : fieldOrPropertyType.ToTypeWithState().State; int valueMemberSlot = -1; if (valueContainerSlot > 0) { valueMemberSlot = VariableSlot(member, valueContainerSlot); if (valueMemberSlot == skipSlot) { return; } value = this.State.HasValue(valueMemberSlot) ? this.State[valueMemberSlot] : NullableFlowState.NotNull; } SetStateAndTrackForFinally(ref this.State, targetMemberSlot, value); if (valueMemberSlot > 0) { InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, skipSlot); } } } else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.Type)) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { int valueMemberSlot = (valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : -1; if (valueMemberSlot == skipSlot) { return; } InheritNullableStateOfTrackableStruct(fieldOrPropertyType.Type, targetMemberSlot, valueMemberSlot, isDefaultValue: isDefaultValue, skipSlot); } } } private TypeSymbol NominalSlotType(int slot) { return _variables[slot].Symbol.GetTypeOrReturnType().Type; } /// <summary> /// Whenever assigning a variable, and that variable is not declared at the point the state is being set, /// and the new state is not <see cref="NullableFlowState.NotNull"/>, this method should be called to perform the /// state setting and to ensure the mutation is visible outside the finally block when the mutation occurs in a /// finally block. /// </summary> private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) { state[slot] = newState; if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) { var tryState = NonMonotonicState.Value; if (tryState.HasVariable(slot)) { tryState[slot] = newState.Join(tryState[slot]); NonMonotonicState = tryState; } } } protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) { var tryState = other.GetStateForVariables(self.Id); Join(ref self, ref tryState); } private void InheritDefaultState(TypeSymbol targetType, int targetSlot) { Debug.Assert(targetSlot > 0); // Reset the state of any members of the target. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, targetSlot); foreach (var (variable, slot) in members) { var symbol = AsMemberOfType(targetType, variable.Symbol); SetStateAndTrackForFinally(ref this.State, slot, GetDefaultState(symbol)); InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot); } members.Free(); } private NullableFlowState GetDefaultState(Symbol symbol) => ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) { Debug.Assert(targetSlot > 0); Debug.Assert(valueSlot > 0); // Clone the state for members that have been set on the value. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, valueSlot); foreach (var (variable, slot) in members) { var member = variable.Symbol; Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); InheritNullableStateOfMember(targetSlot, valueSlot, member, isDefaultValue: false, skipSlot); } members.Free(); } protected override LocalState TopState() { var state = LocalState.ReachableState(_variables); state.PopulateAll(this); return state; } protected override LocalState UnreachableState() { return LocalState.UnreachableState(_variables); } protected override LocalState ReachableBottomState() { // Create a reachable state in which all variables are known to be non-null. return LocalState.ReachableState(_variables); } private void EnterParameters() { if (!(CurrentSymbol is MethodSymbol methodSymbol)) { return; } if (methodSymbol is SynthesizedRecordConstructor) { if (_hasInitialState) { // A record primary constructor's parameters are entered before analyzing initializers. // On the second pass, the correct parameter states (potentially modified by initializers) // are contained in the initial state. return; } } else if (methodSymbol.IsConstructor()) { if (!_hasInitialState) { // For most constructors, we only enter parameters after analyzing initializers. return; } } // The partial definition part may include optional parameters whose default values we want to simulate assigning at the beginning of the method methodSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol; var methodParameters = methodSymbol.Parameters; var signatureParameters = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod! : methodSymbol).Parameters; // save a state representing the possibility that parameter default values were not assigned to the parameters. var parameterDefaultsNotAssignedState = State.Clone(); for (int i = 0; i < methodParameters.Length; i++) { var parameter = methodParameters[i]; // In error scenarios, the method can potentially have more parameters than the signature. If so, use the parameter type for those // errored parameters var parameterType = i >= signatureParameters.Length ? parameter.TypeWithAnnotations : signatureParameters[i].TypeWithAnnotations; EnterParameter(parameter, parameterType); } Join(ref State, ref parameterDefaultsNotAssignedState); } private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) { _variables.SetType(parameter, parameterType); if (parameter.RefKind != RefKind.Out) { int slot = GetOrCreateSlot(parameter); Debug.Assert(!IsConditionalState); if (slot > 0) { var state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; this.State[slot] = state; if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) { InheritNullableStateOfTrackableStruct( parameterType.Type, slot, valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } } } } public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) { var parameter = equalsValue.Parameter; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); var resultType = VisitOptionalImplicitConversion( equalsValue.Value, parameterLValueType, useLegacyWarnings: false, trackMembers: false, assignmentKind: AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); return null; } internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); } if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); } return parameterType.ToTypeWithState(); } public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) { Debug.Assert(!IsConditionalState); var expr = node.ExpressionOpt; if (expr == null) { EnforceDoesNotReturn(node.Syntax); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return null; } // Should not convert to method return type when inferring return type (when _returnTypesOpt != null). if (_returnTypesOpt == null && TryGetReturnType(out TypeWithAnnotations returnType, out FlowAnalysisAnnotations returnAnnotations)) { if (node.RefKind == RefKind.None && returnType.Type.SpecialType == SpecialType.System_Boolean) { // visit the expression without unsplitting, then check parameters marked with flow analysis attributes Visit(expr); } else { TypeWithState returnState; if (node.RefKind == RefKind.None) { returnState = VisitOptionalImplicitConversion(expr, returnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); } else { // return ref expr; returnState = VisitRefExpression(expr, returnType); } // If the return has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(returnState, ToInwardAnnotations(returnAnnotations), node.Syntax.Location, boundValueOpt: expr); } } else { var result = VisitRvalueWithState(expr); if (_returnTypesOpt != null) { _returnTypesOpt.Add((node, result.ToTypeWithAnnotations(compilation))); } } EnforceDoesNotReturn(node.Syntax); if (IsConditionalState) { var joinedState = this.StateWhenTrue.Clone(); Join(ref joinedState, ref this.StateWhenFalse); PendingBranches.Add(new PendingBranch(node, joinedState, label: null, this.IsConditionalState, this.StateWhenTrue, this.StateWhenFalse)); } else { PendingBranches.Add(new PendingBranch(node, this.State, label: null)); } Unsplit(); if (CurrentSymbol is MethodSymbol method) { EnforceNotNullIfNotNull(node.Syntax, this.State, method.Parameters, method.ReturnNotNullIfParameterNotNull, ResultType.State, outputParam: null); } SetUnreachable(); return null; } private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) { Visit(expr); TypeWithState resultType = ResultType; if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) { var lvalueResultType = LvalueResultType; if (IsNullabilityMismatch(lvalueResultType, destinationType)) { // declared types must match ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); } } return resultType; } private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) { var method = CurrentSymbol as MethodSymbol; if (method is null) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } var delegateOrMethod = _useDelegateInvokeReturnType ? _delegateInvokeMethod! : method; var returnType = delegateOrMethod.ReturnTypeWithAnnotations; Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred); if (returnType.IsVoidType()) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } if (!method.IsAsync) { annotations = delegateOrMethod.ReturnTypeFlowAnalysisAnnotations; type = ApplyUnconditionalAnnotations(returnType, annotations); return true; } if (method.IsAsyncEffectivelyReturningGenericTask(compilation)) { type = ((NamedTypeSymbol)returnType.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); annotations = FlowAnalysisAnnotations.None; return true; } type = default; annotations = FlowAnalysisAnnotations.None; return false; } public override BoundNode? VisitLocal(BoundLocal node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); var type = GetDeclaredLocalResult(local); if (!node.Type.Equals(type.Type, TypeCompareKind.ConsiderEverything | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames)) { // When the local is used before or during initialization, there can potentially be a mismatch between node.LocalSymbol.Type and node.Type. We // need to prefer node.Type as we shouldn't be changing the type of the BoundLocal node during rewrite. // https://github.com/dotnet/roslyn/issues/34158 Debug.Assert(node.Type.IsErrorType() || type.Type.IsErrorType()); type = TypeWithAnnotations.Create(node.Type, type.NullableAnnotation); } SetResult(node, GetAdjustedResult(type.ToTypeWithState(), slot), type); SplitIfBooleanConstant(node); return null; } public override BoundNode? VisitBlock(BoundBlock node) { DeclareLocals(node.Locals); VisitStatementsWithLocalFunctions(node); return null; } private void VisitStatementsWithLocalFunctions(BoundBlock block) { // Since the nullable flow state affects type information, and types can be queried by // the semantic model, there needs to be a single flow state input to a local function // that cannot be path-dependent. To decide the local starting state we Meet the state // of captured variables from all the uses of the local function, computing the // conservative combination of all potential starting states. // // For performance we split the analysis into two phases: the first phase where we // analyze everything except the local functions, hoping to visit all of the uses of the // local function, and then a pass where we visit the local functions. If there's no // recursion or calls between the local functions, the starting state of the local // function should be stable and we don't need a second pass. if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) { // First visit everything else foreach (var stmt in block.Statements) { if (stmt.Kind != BoundKind.LocalFunctionStatement) { VisitStatement(stmt); } } // Now visit the local function bodies foreach (var stmt in block.Statements) { if (stmt is BoundLocalFunctionStatement localFunc) { VisitLocalFunctionStatement(localFunc); } } } else { foreach (var stmt in block.Statements) { VisitStatement(stmt); } } } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var localFunc = node.Symbol; var localFunctionState = GetOrCreateLocalFuncUsages(localFunc); // The starting state is the top state, but with captured // variables set according to Joining the state at all the // local function use sites var state = TopState(); var startingState = localFunctionState.StartingState; startingState.ForEach( (slot, variables) => { var symbol = variables[variables.RootSlot(slot)].Symbol; if (Symbol.IsCaptured(symbol, localFunc)) { state[slot] = startingState[slot]; } }, _variables); localFunctionState.Visited = true; AnalyzeLocalFunctionOrLambda( node, localFunc, state, delegateInvokeMethod: null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); SetInvalidResult(); return null; } private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) { _nestedFunctionVariables ??= PooledDictionary<MethodSymbol, Variables>.GetInstance(); if (!_nestedFunctionVariables.TryGetValue(lambdaOrLocalFunction, out var variables)) { variables = container.CreateNestedMethodScope(lambdaOrLocalFunction); _nestedFunctionVariables.Add(lambdaOrLocalFunction, variables); } Debug.Assert((object?)variables.Container == container); return variables; } private void AnalyzeLocalFunctionOrLambda( IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethod is object); Debug.Assert(!useDelegateInvokeReturnType || delegateInvokeMethod is object); var oldSymbol = this.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; var oldState = this.State; _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); this.State = state.CreateNestedMethodState(_variables); var previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? -1; try { var oldPending = SavePending(); EnterParameters(); var oldPending2 = SavePending(); // If this is an iterator, there's an implicit branch before the first statement // of the function where the enumerable is returned. if (lambdaOrFunctionSymbol.IsIterator) { PendingBranches.Add(new PendingBranch(null, this.State, null)); } VisitAlways(lambdaOrFunction.Body); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = oldSymbol; } protected override void VisitLocalFunctionUse( LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { // Do not use this overload in NullableWalker. Use the overload below instead. throw ExceptionUtilities.Unreachable; } private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) { Debug.Assert(!IsConditionalState); var localFunctionState = GetOrCreateLocalFuncUsages(symbol); var state = State.GetStateForVariables(localFunctionState.StartingState.Id); if (Join(ref localFunctionState.StartingState, ref state) && localFunctionState.Visited) { // If the starting state of the local function has changed and we've already visited // the local function, we need another pass stateChangedAfterUse = true; } } public override BoundNode? VisitDoStatement(BoundDoStatement node) { DeclareLocals(node.Locals); return base.VisitDoStatement(node); } public override BoundNode? VisitWhileStatement(BoundWhileStatement node) { DeclareLocals(node.Locals); return base.VisitWhileStatement(node); } public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) { Debug.Assert(!IsConditionalState); var receiver = withExpr.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); var resultType = withExpr.CloneMethod?.ReturnTypeWithAnnotations ?? ResultType.ToTypeWithAnnotations(compilation); var resultState = ApplyUnconditionalAnnotations(resultType.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); var resultSlot = GetOrCreatePlaceholderSlot(withExpr); // carry over the null state of members of 'receiver' to the result of the with-expression. TrackNullableStateForAssignment(receiver, resultType, resultSlot, resultState, MakeSlot(receiver)); // use the declared nullability of Clone() for the top-level nullability of the result of the with-expression. SetResult(withExpr, resultState, resultType); VisitObjectCreationInitializer(containingSymbol: null, resultSlot, withExpr.InitializerExpression, FlowAnalysisAnnotations.None); // Note: this does not account for the scenario where `Clone()` returns maybe-null and the with-expression has no initializers. // Tracking in https://github.com/dotnet/roslyn/issues/44759 return null; } public override BoundNode? VisitForStatement(BoundForStatement node) { DeclareLocals(node.OuterLocals); DeclareLocals(node.InnerLocals); return base.VisitForStatement(node); } public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); return base.VisitForEachStatement(node); } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { DeclareLocals(node.Locals); Visit(node.AwaitOpt); return base.VisitUsingStatement(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { Visit(node.AwaitOpt); return base.VisitUsingLocalDeclarations(node); } public override BoundNode? VisitFixedStatement(BoundFixedStatement node) { DeclareLocals(node.Locals); return base.VisitFixedStatement(node); } public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) { DeclareLocals(node.Locals); return base.VisitConstructorMethodBody(node); } private void DeclareLocal(LocalSymbol local) { if (local.DeclarationKind != LocalDeclarationKind.None) { int slot = GetOrCreateSlot(local); if (slot > 0) { this.State[slot] = GetDefaultState(ref this.State, slot); InheritDefaultState(GetDeclaredLocalResult(local).Type, slot); } } } private void DeclareLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { DeclareLocal(local); } } public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); // We need visit the optional arguments so that we can return nullability information // about them, but we don't want to communicate any information about anything underneath. // Additionally, tests like Scope_DeclaratorArguments_06 can have conditional expressions // in the optional arguments that can leave us in a split state, so we want to make sure // we are not in a conditional state after. Debug.Assert(!IsConditionalState); var oldDisable = _disableDiagnostics; _disableDiagnostics = true; var currentState = State; VisitAndUnsplitAll(node.ArgumentsOpt); _disableDiagnostics = oldDisable; SetState(currentState); if (node.DeclaredTypeOpt != null) { VisitTypeExpression(node.DeclaredTypeOpt); } var initializer = node.InitializerOpt; if (initializer is null) { return null; } TypeWithAnnotations type = local.TypeWithAnnotations; TypeWithState valueType; bool inferredType = node.InferredType; if (local.IsRef) { valueType = VisitRefExpression(initializer, type); } else { valueType = VisitOptionalImplicitConversion(initializer, targetTypeOpt: inferredType ? default : type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } if (inferredType) { if (valueType.HasNullType) { Debug.Assert(type.Type.IsErrorType()); valueType = type.ToTypeWithState(); } type = valueType.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local, type); if (node.DeclaredTypeOpt != null) { SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(type.ToTypeWithState(), type), true); } } TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer)); return null; } protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { Debug.Assert(!IsConditionalState); SetInvalidResult(); _ = base.VisitExpressionWithoutStackGuard(node); TypeWithState resultType = ResultType; #if DEBUG // Verify Visit method set _result. Debug.Assert((object?)resultType.Type != _invalidType.Type); Debug.Assert(AreCloseEnough(resultType.Type, node.Type)); #endif if (ShouldMakeNotNullRvalue(node)) { var result = resultType.WithNotNullState(); SetResult(node, result, LvalueResultType); } return null; } #if DEBUG // For asserts only. private static bool AreCloseEnough(TypeSymbol? typeA, TypeSymbol? typeB) { // https://github.com/dotnet/roslyn/issues/34993: We should be able to tighten this to ensure that we're actually always returning the same type, // not error if one is null or ignoring certain types if ((object?)typeA == typeB) { return true; } if (typeA is null || typeB is null) { return typeA?.IsErrorType() != false && typeB?.IsErrorType() != false; } return canIgnoreAnyType(typeA) || canIgnoreAnyType(typeB) || typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(type).Any(t => canIgnoreAnyType(t.Type)); } } private static bool AreCloseEnough(Symbol original, Symbol updated) { // When https://github.com/dotnet/roslyn/issues/38195 is fixed, this workaround needs to be removed if (original is ConstructedMethodSymbol || updated is ConstructedMethodSymbol) { return AreCloseEnough(original.OriginalDefinition, updated.OriginalDefinition); } return (original, updated) switch { (LambdaSymbol l, NamedTypeSymbol n) _ when n.IsDelegateType() => AreLambdaAndNewDelegateSimilar(l, n), (FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var oi } originalField, FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var ui } updatedField) => originalField.Type.Equals(updatedField.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) && oi == ui, _ => original.Equals(updated, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) }; } #endif private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) { var invokeMethod = n.DelegateInvokeMethod; return invokeMethod.Parameters.SequenceEqual(l.Parameters, (p1, p2) => p1.Type.Equals(p2.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) && invokeMethod.ReturnType.Equals(l.ReturnType, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames); } public override BoundNode? Visit(BoundNode? node) { return Visit(node, expressionIsRead: true); } private BoundNode VisitLValue(BoundNode node) { return Visit(node, expressionIsRead: false); } private BoundNode Visit(BoundNode? node, bool expressionIsRead) { bool originalExpressionIsRead = _expressionIsRead; _expressionIsRead = expressionIsRead; TakeIncrementalSnapshot(node); var result = base.Visit(node); _expressionIsRead = originalExpressionIsRead; return result; } protected override void VisitStatement(BoundStatement statement) { SetInvalidResult(); base.VisitStatement(statement); SetInvalidResult(); } public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { // This method is only involved in method inference with unbound lambdas. // The diagnostics on arguments are reported by VisitObjectCreationExpression. SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); return null; } private void VisitObjectOrDynamicObjectCreation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, BoundExpression? initializerOpt) { Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression || node.Kind == BoundKind.NewT); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var type = node.Type; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { var boundObjectCreationExpression = node as BoundObjectCreationExpression; var constructor = boundObjectCreationExpression?.Constructor; bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor(requireZeroInit: true) == true; if (EmptyStructTypeCache.IsTrackableStructType(type)) { var containingType = constructor?.ContainingType; if (containingType?.IsTupleType == true && !isDefaultValueTypeConstructor) { // new System.ValueTuple<T1, ..., TN>(e1, ..., eN) TrackNullableStateOfTupleElements(slot, containingType, arguments, argumentTypes, boundObjectCreationExpression!.ArgsToParamsOpt, useRestField: true); } else { InheritNullableStateOfTrackableStruct( type, slot, valueSlot: -1, isDefaultValue: isDefaultValueTypeConstructor); } } else if (type.IsNullableType()) { if (isDefaultValueTypeConstructor) { // a nullable value type created with its default constructor is by definition null resultState = NullableFlowState.MaybeNull; } else if (constructor?.ParameterCount == 1) { // if we deal with one-parameter ctor that takes underlying, then Value state is inferred from the argument. var parameterType = constructor.ParameterTypesWithAnnotations[0]; if (AreNullableAndUnderlyingTypes(type, parameterType.Type, out TypeWithAnnotations underlyingType)) { var operand = arguments[0]; int valueSlot = MakeSlot(operand); if (valueSlot > 0) { TrackNullableStateOfNullableValue(slot, type, operand, underlyingType.ToTypeWithState(), valueSlot); } } } } this.State[slot] = resultState; } } if (initializerOpt != null) { VisitObjectCreationInitializer(containingSymbol: null, slot, initializerOpt, leftAnnotations: FlowAnalysisAnnotations.None); } SetResultType(node, TypeWithState.Create(type, resultState)); } private void VisitObjectCreationInitializer(Symbol? containingSymbol, int containingSlot, BoundExpression node, FlowAnalysisAnnotations leftAnnotations) { TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: checkImplicitReceiver(objectInitializer); foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: VisitObjectElementInitializer(containingSlot, (BoundAssignmentOperator)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: checkImplicitReceiver(collectionInitializer); foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: Debug.Assert(containingSymbol is object); if (containingSymbol is object) { var type = ApplyLValueAnnotations(containingSymbol.GetTypeOrReturnType(), leftAnnotations); TypeWithState resultType = VisitOptionalImplicitConversion(node, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment); TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node)); } break; } void checkImplicitReceiver(BoundObjectInitializerExpressionBase node) { if (containingSlot >= 0 && !node.Initializers.IsEmpty) { if (!node.Type.IsValueType && State[containingSlot].MayBeNull()) { if (containingSymbol is null) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, node.Syntax); } else { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, node.Syntax, containingSymbol); } } } } } private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOperator node) { TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { var objectInitializer = (BoundObjectInitializerMember)left; TakeIncrementalSnapshot(left); var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) { int slot = (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); VisitObjectCreationInitializer(symbol, slot, node.Right, GetLValueAnnotations(node.Left)); // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); } break; default: Visit(node); break; } } private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { Debug.Assert(node.ImplicitReceiverOpt.Kind == BoundKind.ObjectOrCollectionValuePlaceholder); SetAnalyzedNullability(node.ImplicitReceiverOpt, new VisitResult(node.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); } SetUnknownResultNullability(node); SetUpdatedSymbol(node, node.AddMethod, reinferredMethod); } private void SetNotNullResult(BoundExpression node) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); } /// <summary> /// Returns true if the type is a struct with no fields or properties. /// </summary> protected override bool IsEmptyStructType(TypeSymbol type) { if (type.TypeKind != TypeKind.Struct) { return false; } // EmptyStructTypeCache.IsEmptyStructType() returns false // if there are non-cyclic fields. if (!_emptyStructTypeCache.IsEmptyStructType(type)) { return false; } if (type.SpecialType != SpecialType.None) { return true; } var members = ((NamedTypeSymbol)type).GetMembersUnordered(); // EmptyStructTypeCache.IsEmptyStructType() returned true. If there are fields, // at least one of those fields must be cyclic, so treat the type as empty. if (members.Any(m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(m => m.Kind == SymbolKind.Property)) { return false; } return true; } private int GetOrCreatePlaceholderSlot(BoundExpression node) { Debug.Assert(node.Type is object); if (IsEmptyStructType(node.Type)) { return -1; } return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); } private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) { _placeholderLocalsOpt ??= PooledDictionary<object, PlaceholderLocal>.GetInstance(); if (!_placeholderLocalsOpt.TryGetValue(identifier, out var placeholder)) { placeholder = new PlaceholderLocal(CurrentSymbol, identifier, type); _placeholderLocalsOpt.Add(identifier, placeholder); } Debug.Assert((object)placeholder != null); return GetOrCreateSlot(placeholder, forceSlotEvenIfEmpty: true); } public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { Debug.Assert(!IsConditionalState); Debug.Assert(node.Type.IsAnonymousType); var anonymousType = (NamedTypeSymbol)node.Type; var arguments = node.Arguments; var argumentTypes = arguments.SelectAsArray((arg, self) => self.VisitRvalueWithState(arg), this); var argumentsWithAnnotations = argumentTypes.SelectAsArray(arg => arg.ToTypeWithAnnotations(compilation)); if (argumentsWithAnnotations.All(argType => argType.HasType)) { anonymousType = AnonymousTypeManager.ConstructAnonymousTypeSymbol(anonymousType, argumentsWithAnnotations); int receiverSlot = GetOrCreatePlaceholderSlot(node); int currentDeclarationIndex = 0; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var argumentType = argumentTypes[i]; var property = AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, i); if (property.Type.SpecialType != SpecialType.System_Void) { // A void element results in an error type in the anonymous type but not in the property's container! // To avoid failing an assertion later, we skip them. var slot = GetOrCreateSlot(property, receiverSlot); TrackNullableStateForAssignment(argument, property.TypeWithAnnotations, slot, argumentType, MakeSlot(argument)); var currentDeclaration = getDeclaration(node, property, ref currentDeclarationIndex); if (currentDeclaration is object) { TakeIncrementalSnapshot(currentDeclaration); SetAnalyzedNullability(currentDeclaration, new VisitResult(argumentType, property.TypeWithAnnotations)); } } } } SetResultType(node, TypeWithState.Create(anonymousType, NullableFlowState.NotNull)); return null; static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression node, PropertySymbol currentProperty, ref int currentDeclarationIndex) { if (currentDeclarationIndex >= node.Declarations.Length) { return null; } var currentDeclaration = node.Declarations[currentDeclarationIndex]; if (currentDeclaration.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) { currentDeclarationIndex++; return currentDeclaration; } return null; } } public override BoundNode? VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } TakeIncrementalSnapshot(initialization); var expressions = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length); GetArrayElements(initialization, expressions); int n = expressions.Count; // Consider recording in the BoundArrayCreation // whether the array was implicitly typed, rather than relying on syntax. bool isInferred = node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression; var arrayType = (ArrayTypeSymbol)node.Type; var elementType = arrayType.ElementTypeWithAnnotations; if (!isInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(n); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); foreach (var expression in expressions) { // collect expressions, conversions and result types (BoundExpression expressionNoConversion, Conversion conversion) = RemoveConversion(expression, includeExplicitConversions: false); expressionsNoConversions.Add(expressionNoConversion); conversions.Add(conversion); SnapshotWalkerThroughConversionGroup(expression, expressionNoConversion); var resultType = VisitRvalueWithState(expressionNoConversion); resultTypes.Add(resultType); placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, resultType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!node.HasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo); } TypeWithAnnotations inferredType = (bestType is null) ? elementType.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(bestType); if (bestType is object) { // Convert elements to best type to determine element top-level nullability and to report nested nullability warnings for (int i = 0; i < n; i++) { var expressionNoConversion = expressionsNoConversions[i]; var expression = GetConversionIfApplicable(expressions[i], expressionNoConversion); resultTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false); } // Set top-level nullability on inferred element type var elementState = BestTypeInferrer.GetNullableState(resultTypes); inferredType = TypeWithState.Create(inferredType.Type, elementState).ToTypeWithAnnotations(compilation); for (int i = 0; i < n; i++) { // Report top-level warnings _ = VisitConversion(conversionOpt: null, conversionOperand: expressionsNoConversions[i], Conversion.Identity, targetTypeWithNullability: inferredType, operandType: resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false); } } else { // We need to ensure that we're tracking the inferred type with nullability of any conversions that // were stripped off. for (int i = 0; i < n; i++) { TrackAnalyzedNullabilityThroughConversionGroup(inferredType.ToTypeWithState(), expressions[i] as BoundConversion, expressionsNoConversions[i]); } } expressionsNoConversions.Free(); conversions.Free(); resultTypes.Free(); arrayType = arrayType.WithElementType(inferredType); } expressions.Free(); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } /// <summary> /// Applies analysis similar to <see cref="VisitArrayCreation"/>. /// The expressions returned from a lambda are not converted though, so we'll have to classify fresh conversions. /// Note: even if some conversions fail, we'll proceed to infer top-level nullability. That is reasonable in common cases. /// </summary> internal static TypeWithAnnotations BestTypeForLambdaReturns( ArrayBuilder<(BoundExpression, TypeWithAnnotations)> returns, Binder binder, BoundNode node, Conversions conversions) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: null, returnTypesOpt: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); int n = returns.Count; var resultTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); var placeholdersBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var (returnExpr, resultType) = returns[i]; resultTypes.Add(resultType); placeholdersBuilder.Add(CreatePlaceholderIfNecessary(returnExpr, resultType)); } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var placeholders = placeholdersBuilder.ToImmutableAndFree(); TypeSymbol? bestType = BestTypeInferrer.InferBestType(placeholders, walker._conversions, ref discardedUseSiteInfo); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); ConversionsBase conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, ref discardedUseSiteInfo); resultTypes[i] = walker.VisitConversion(conversionOpt: null, placeholder, conversion, bestTypeWithObliviousAnnotation, resultTypes[i].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, reportRemainingWarnings: false, reportTopLevelWarnings: false).ToTypeWithAnnotations(binder.Compilation); } // Set top-level nullability on inferred type inferredType = TypeWithAnnotations.Create(bestType, BestTypeInferrer.GetNullableAnnotation(resultTypes)); } else { inferredType = default; } resultTypes.Free(); walker.Free(); return inferredType; } private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { GetArrayElements((BoundArrayInitialization)child, builder); } else { builder.Add(child); } } } public override BoundNode? VisitArrayAccess(BoundArrayAccess node) { Debug.Assert(!IsConditionalState); Visit(node.Expression); Debug.Assert(!IsConditionalState); Debug.Assert(!node.Expression.Type!.IsValueType); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(node.Expression); var type = ResultType.Type as ArrayTypeSymbol; foreach (var i in node.Indices) { VisitRvalue(i); } TypeWithAnnotations result; if (node.Indices.Length == 1 && TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything2)) { result = TypeWithAnnotations.Create(type); } else { result = type?.ElementTypeWithAnnotations ?? default; } SetLvalueResultType(node, result); return null; } private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) { NullableFlowState resultState = NullableFlowState.NotNull; if (operatorKind.IsUserDefined()) { if (methodOpt?.ParameterCount == 2) { if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); } var resultTypeWithState = GetReturnTypeWithState(methodOpt); if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) { resultTypeWithState = resultTypeWithState.WithNotNullState(); } return resultTypeWithState; } } else if (!operatorKind.IsDynamic() && !resultType.IsValueType) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.DelegateCombination: resultState = leftType.State.Meet(rightType.State); break; case BinaryOperatorKind.DelegateRemoval: resultState = NullableFlowState.MaybeNull; // Delegate removal can produce null. break; default: resultState = NullableFlowState.NotNull; break; } } if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { resultState = leftType.State.Join(rightType.State); } return TypeWithState.Create(resultType, resultState); } protected override void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); var (leftOperand, leftConversion) = RemoveConversion(binary.Left, includeExplicitConversions: false); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(leftOperand, out var conditionalStateWhenNotNull) && CanPropagateStateWhenNotNull(leftConversion) && binary.OperatorKind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // Consider the following two scenarios: // `a?.b(x = new object()) == c.d(x = null)` // `x` is maybe-null after expression // `a?.b(x = null) == c.d(x = new object())` // `x` is not-null after expression // In this scenario, we visit the RHS twice: // (1) Once using the single "stateWhenNotNull" after the LHS, in order to update the "stateWhenNotNull" with the effects of the RHS // (2) Once using the "worst case" state after the LHS for diagnostics and public API // After the two visits of the RHS, we may set a conditional state using the state after (1) as the StateWhenTrue and the state after (2) as the StateWhenFalse. // Depending on whether `==` or `!=` was used, and depending on the value of the RHS, we may then swap the StateWhenTrue with the StateWhenFalse. var oldDisableDiagnostics = _disableDiagnostics; _disableDiagnostics = true; var stateAfterLeft = this.State; SetState(getUnconditionalStateWhenNotNull(rightOperand, conditionalStateWhenNotNull)); VisitRvalue(rightOperand); var stateWhenNotNull = this.State; _disableDiagnostics = oldDisableDiagnostics; // Now visit the right side for public API and diagnostics using the worst-case state from the LHS. // Note that we do this visit last to try and make sure that the "visit for public API" overwrites walker state recorded during previous visits where possible. SetState(stateAfterLeft); var rightType = VisitRvalueWithState(rightOperand); ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); if (isKnownNullOrNotNull(rightOperand, rightType)) { var isNullConstant = rightOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } if (stack.Count == 0) { return; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } while (true) { if (!learnFromConditionalAccessOrBoolConstant()) { Unsplit(); // VisitRvalue does this UseRvalueOnly(leftOperand); // drop lvalue part AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); } if (stack.Count == 0) { break; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState resultType) { return resultType.State.IsNotNull() || expr.ConstantValue is object; } LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) { LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else if (isEquals(binary) && otherOperand.ConstantValue is { IsBoolean: true, BooleanValue: var boolValue }) { // can preserve conditional state from `.TryGetValue` in `dict?.TryGetValue(key, out value) == true`, // but not in `dict?.TryGetValue(key, out value) != false` stateWhenNotNull = boolValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } return stateWhenNotNull; } // Returns true if `binary.Right` was visited by the call. bool learnFromConditionalAccessOrBoolConstant() { if (binary.OperatorKind.Operator() is not (BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual)) { return false; } var leftResult = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // `true == a?.b(out x)` if (isKnownNullOrNotNull(leftOperand, leftResult) && CanPropagateStateWhenNotNull(rightConversion) && TryVisitConditionalAccess(rightOperand, out var conditionalStateWhenNotNull)) { ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftResult, rightOperand, rightConversion, rightType: ResultType, binary); var stateWhenNotNull = getUnconditionalStateWhenNotNull(leftOperand, conditionalStateWhenNotNull); var isNullConstant = leftOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // can only learn from a bool constant operand here if it's using the built in `bool operator ==(bool left, bool right)` if (binary.OperatorKind.IsUserDefined()) { return false; } // `(x != null) == true` if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); // record result for the right SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); } // `true == (x != null)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { return false; } // record result for the binary Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); return true; } } private void ReinferBinaryOperatorAndSetResult( BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); // At this point, State.Reachable may be false for // invalid code such as `s + throw new Exception()`. var method = binary.Method; if (binary.OperatorKind.IsUserDefined() && method?.ParameterCount == 2) { // Update method based on inferred operand type. TypeSymbol methodContainer = method.ContainingType; bool isLifted = binary.OperatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); TypeSymbol? asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type); if (asMemberOfType is object) { method = (MethodSymbol)AsMemberOfType(asMemberOfType, method); } // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameters = method.Parameters; visitOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { TypeWithAnnotations targetTypeWithNullability = parameter.TypeWithAnnotations; if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } _ = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); } } else { // Assume this is a built-in operator in which case the parameter types are unannotated. visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) { if (expr.Type is null) { Debug.Assert(operand == expr); } else { _ = VisitConversion( expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); } } } Debug.Assert(!IsConditionalState); // For nested binary operators, this can be the only time they're visited due to explicit stack used in AbstractFlowPass.VisitBinaryOperator, // so we need to set the flow-analyzed type here. var inferredResult = InferResultNullability(binary.OperatorKind, method, binary.Type, leftType, rightType); SetResult(binary, inferredResult, inferredResult.ToTypeWithAnnotations(compilation)); TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType) { if (derivedType is null) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, ref discardedUseSiteInfo); if (conversion.Exists && !conversion.IsExplicit) { return derivedType; } return null; } } private void AfterLeftChildHasBeenVisited( BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); VisitRvalue(rightOperand); var rightType = ResultType; ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); BinaryOperatorKind op = binary.OperatorKind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { // learn from null constant BoundExpression? operandComparedToNull = null; if (binary.Right.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Left; } else if (binary.Left.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Right; } if (operandComparedToNull != null) { // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c. bool nonNullCase = op != BinaryOperatorKind.Equal; // true represents WhenTrue splitAndLearnFromNonNullTest(operandComparedToNull, whenTrue: nonNullCase); // `x == null` and `x != null` are pure null tests so update the null-state in the alternative branch too LearnFromNullTest(operandComparedToNull, ref nonNullCase ? ref StateWhenFalse : ref StateWhenTrue); return; } } // learn from comparison between non-null and maybe-null, possibly updating maybe-null to non-null BoundExpression? operandComparedToNonNull = null; if (leftType.IsNotNull && rightType.MayBeNull) { operandComparedToNonNull = binary.Right; } else if (rightType.IsNotNull && leftType.MayBeNull) { operandComparedToNonNull = binary.Left; } if (operandComparedToNonNull != null) { switch (op) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: true); return; case BinaryOperatorKind.NotEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: false); return; }; } void splitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) { var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(operandComparedToNonNull, slotBuilder); if (slotBuilder.Count != 0) { Split(); ref LocalState stateToUpdate = ref whenTrue ? ref this.StateWhenTrue : ref this.StateWhenFalse; MarkSlotsAsNotNull(slotBuilder, ref stateToUpdate); } slotBuilder.Free(); } } protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) { var result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); SetNotNullResult(node); return result; } protected override void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) { SetNotNullResult(node); } /// <summary> /// If we learn that the operand is non-null, we can infer that certain /// sub-expressions were also non-null. /// Get all nested conditional slots for those sub-expressions. For example in a?.b?.c we'll set a, b, and c. /// Only returns slots for tracked expressions. /// </summary> /// <remarks>https://github.com/dotnet/roslyn/issues/53397 This method should potentially be removed.</remarks> private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder<int> slotBuilder) { Debug.Assert(operand != null); var previousConditionalAccessSlot = _lastConditionalAccessSlot; try { while (true) { // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree, // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot // for, nothing underneath is trackable and we bail at that point. Example: // // a?.GetB()?.C // a is a field, GetB is a method, and C is a property // // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because // fields have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll // return an array with just the slot for a. int slot; switch (operand.Kind) { case BoundKind.Conversion: // https://github.com/dotnet/roslyn/issues/33879 Detect when conversion has a nullable operand operand = ((BoundConversion)operand).Operand; continue; case BoundKind.AsOperator: operand = ((BoundAsOperator)operand).Operand; continue; case BoundKind.ConditionalAccess: var conditional = (BoundConditionalAccess)operand; GetSlotsToMarkAsNotNullable(conditional.Receiver, slotBuilder); slot = MakeSlot(conditional.Receiver); if (slot > 0) { // We need to continue the walk regardless of whether the receiver should be updated. var receiverType = conditional.Receiver.Type!; if (receiverType.IsNullableType()) slot = GetNullableOfTValueSlot(receiverType, slot, out _); } if (slot > 0) { // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers // until it gets to the BoundConditionalReceiver associated with this node. In our override // of MakeSlot, we substitute this slot when we encounter a BoundConditionalReceiver, and reset the // _lastConditionalAccess field. _lastConditionalAccessSlot = slot; operand = conditional.AccessExpression; continue; } // If there's no slot for this receiver, there cannot be another slot for any of the remaining // access expressions. break; default: // Attempt to create a slot for the current thing. If there were any more conditional accesses, // they would have been on top, so this is the last thing we need to specially handle. // https://github.com/dotnet/roslyn/issues/33879 When we handle unconditional access survival (ie after // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether // we need more special handling here slot = MakeSlot(operand); if (slot > 0 && PossiblyNullableType(operand.Type)) { slotBuilder.Add(slot); } break; } return; } } finally { _lastConditionalAccessSlot = previousConditionalAccessSlot; } } private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) => operandType?.CanContainNull() == true; private static void MarkSlotsAsNotNull(ArrayBuilder<int> slots, ref LocalState stateToUpdate) { foreach (int slot in slots) { stateToUpdate[slot] = NullableFlowState.NotNull; } } private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) { if (expression.Kind == BoundKind.AwaitableValuePlaceholder) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue((BoundAwaitableValuePlaceholder)expression, out var value)) { expression = value.AwaitableExpression; } else { return; } } var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(expression, slotBuilder); MarkSlotsAsNotNull(slotBuilder, ref state); slotBuilder.Free(); } private void LearnFromNonNullTest(int slot, ref LocalState state) { state[slot] = NullableFlowState.NotNull; } private void LearnFromNullTest(BoundExpression expression, ref LocalState state) { // nothing to learn about a constant if (expression.ConstantValue != null) return; // We should not blindly strip conversions here. Tracked by https://github.com/dotnet/roslyn/issues/36164 var expressionWithoutConversion = RemoveConversion(expression, includeExplicitConversions: true).expression; var slot = MakeSlot(expressionWithoutConversion); // Since we know for sure the slot is null (we just tested it), we know that dependent slots are not // reachable and therefore can be treated as not null. However, we have not computed the proper // (inferred) type for the expression, so we cannot compute the correct symbols for the member slots here // (using the incorrect symbols would result in computing an incorrect default state for them). // Therefore we do not mark dependent slots not null. See https://github.com/dotnet/roslyn/issues/39624 LearnFromNullTest(slot, expressionWithoutConversion.Type, ref state, markDependentSlotsNotNull: false); } private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) { if (slot > 0 && PossiblyNullableType(expressionType)) { if (state[slot] == NullableFlowState.NotNull) { // Note: We leave a MaybeDefault state as-is state[slot] = NullableFlowState.MaybeNull; } if (markDependentSlotsNotNull) { MarkDependentSlotsNotNull(slot, expressionType, ref state); } } } // If we know for sure that a slot contains a null value, then we know for sure that dependent slots // are "unreachable" so we might as well treat them as not null. That way when this state is merged // with another state, those dependent states won't pollute values from the other state. private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) { if (depth <= 0) return; foreach (var member in getMembers(expressionType)) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var containingType = this._symbol?.ContainingType; if ((member is PropertySymbol { IsIndexedProperty: false } || member.Kind == SymbolKind.Field) && member.RequiresInstanceReceiver() && (containingType is null || AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))) { int childSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); if (childSlot > 0) { state[childSlot] = NullableFlowState.NotNull; MarkDependentSlotsNotNull(childSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); } } } static IEnumerable<Symbol> getMembers(TypeSymbol type) { // First, return the direct members foreach (var member in type.GetMembers()) yield return member; // All types inherit members from their effective bases for (NamedTypeSymbol baseType = effectiveBase(type); !(baseType is null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) foreach (var member in baseType.GetMembers()) yield return member; // Interfaces and type parameters inherit from their effective interfaces foreach (NamedTypeSymbol interfaceType in inheritedInterfaces(type)) foreach (var member in interfaceType.GetMembers()) yield return member; yield break; static NamedTypeSymbol effectiveBase(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.EffectiveBaseClassNoUseSiteDiagnostics, var t => t.BaseTypeNoUseSiteDiagnostics, }; static ImmutableArray<NamedTypeSymbol> inheritedInterfaces(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.AllEffectiveInterfacesNoUseSiteDiagnostics, { TypeKind: TypeKind.Interface } => type.AllInterfacesNoUseSiteDiagnostics, _ => ImmutableArray<NamedTypeSymbol>.Empty, }; } } private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) { while (possiblyConversion.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)possiblyConversion; switch (conversion.ConversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: possiblyConversion = conversion.Operand; break; default: return possiblyConversion; } } return possiblyConversion; } public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; int leftSlot = MakeSlot(leftOperand); TypeWithAnnotations targetType = VisitLvalueWithAnnotations(leftOperand); var leftState = this.State.Clone(); LearnFromNonNullTest(leftOperand, ref leftState); LearnFromNullTest(leftOperand, ref this.State); if (node.IsNullableValueTypeAssignment) { targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); } TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand, targetType), trackMembers: false, AssignmentKind.Assignment); TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand)); Join(ref this.State, ref leftState); TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State); SetResultType(node, resultType); return null; } public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { Debug.Assert(!IsConditionalState); BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; if (IsConstantNull(leftOperand)) { VisitRvalue(leftOperand); Visit(rightOperand); var rightUnconditionalResult = ResultType; // Should be able to use rightResult for the result of the operator but // binding may have generated a different result type in the case of errors. SetResultType(node, TypeWithState.Create(node.Type, rightUnconditionalResult.State)); return null; } VisitPossibleConditionalAccess(leftOperand, out var whenNotNull); TypeWithState leftResult = ResultType; Unsplit(); LearnFromNullTest(leftOperand, ref this.State); bool leftIsConstant = leftOperand.ConstantValue != null; if (leftIsConstant) { SetUnreachable(); } Visit(rightOperand); TypeWithState rightResult = ResultType; Join(ref whenNotNull); var leftResultType = leftResult.Type; var rightResultType = rightResult.Type; var (resultType, leftState) = node.OperatorResultKind switch { BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightDynamicType => (rightResultType!, NullableFlowState.NotNull), _ => throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind), }; SetResultType(node, TypeWithState.Create(resultType, rightResult.State.Join(leftState))); return null; (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) { Debug.Assert(rightType is object); // If there was an identity conversion between the two operands (in short, if there // is no implicit conversion on the right operand), then check nullable conversions // in both directions since it's possible the right operand is the better result type. if ((node.RightOperand as BoundConversion)?.ExplicitCastInCode != false && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true); Debug.Assert(!conversion.IsUserDefined); return (leftType, NullableFlowState.NotNull); } (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) { var conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true); if (conversion.IsUserDefined) { var conversionResult = VisitConversion( conversionOpt: null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), // When considering the conversion on the left node, it can only occur in the case where the underlying // execution returned non-null TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: false); Debug.Assert(conversionResult.Type is not null); return (conversionResult.Type!, conversionResult.State); } return (rightType, NullableFlowState.NotNull); } } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { var (operand, conversion) = RemoveConversion(node, includeExplicitConversions: true); if (operand is not BoundConditionalAccess access || !CanPropagateStateWhenNotNull(conversion)) { stateWhenNotNull = default; return false; } Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); if (node is BoundConversion boundConversion) { var operandType = ResultType; TypeWithAnnotations explicitType = boundConversion.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(boundConversion.Type); Debug.Assert(targetType.HasType); var result = VisitConversion(boundConversion, access, conversion, targetType, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, assignmentKind: AssignmentKind.Assignment); SetResultType(boundConversion, result); } Debug.Assert(!IsConditionalState); return true; } /// <summary> /// Unconditionally visits an expression and returns the "state when not null" for the expression. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } // in case we *didn't* have a conditional access, the only thing we learn in the "state when not null" // is that the top-level expression was non-null. Visit(node); stateWhenNotNull = PossiblyConditionalState.Create(this); (node, _) = RemoveConversion(node, includeExplicitConversions: true); var slot = MakeSlot(node); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenTrue); LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenFalse); } else { LearnFromNonNullTest(slot, ref stateWhenNotNull.State); } } return false; } private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) { Debug.Assert(!IsConditionalState); var receiver = node.Receiver; // handle scenarios like `(a?.b)?.c()` VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); Unsplit(); _currentConditionalReceiverVisitResult = _visitResult; var previousConditionalAccessSlot = _lastConditionalAccessSlot; if (receiver.ConstantValue is { IsNull: false }) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); } else { var savedState = this.State.Clone(); if (IsConstantNull(receiver)) { SetUnreachable(); _lastConditionalAccessSlot = -1; } else { // In the when-null branch, the receiver is known to be maybe-null. // In the other branch, the receiver is known to be non-null. LearnFromNullTest(receiver, ref savedState); makeAndAdjustReceiverSlot(receiver); SetPossiblyConditionalState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); VisitRvalue(innerCondAccess.Receiver); _currentConditionalReceiverVisitResult = _visitResult; makeAndAdjustReceiverSlot(innerCondAccess.Receiver); // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); Visit(expr); expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // The resulting nullability of each nested conditional access is the same as the resulting nullability of the rightmost access. SetAnalyzedNullability(innerCondAccess, _visitResult); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); var slot = MakeSlot(expr); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref StateWhenTrue); LearnFromNonNullTest(slot, ref StateWhenFalse); } else { LearnFromNonNullTest(slot, ref State); } } stateWhenNotNull = PossiblyConditionalState.Create(this); Unsplit(); Join(ref this.State, ref savedState); } var accessTypeWithAnnotations = LvalueResultType; TypeSymbol accessType = accessTypeWithAnnotations.Type; var oldType = node.Type; var resultType = oldType.IsVoidType() || oldType.IsErrorType() ? oldType : oldType.IsNullableType() && !accessType.IsNullableType() ? MakeNullableOf(accessTypeWithAnnotations) : accessType; // Per LDM 2019-02-13 decision, the result of a conditional access "may be null" even if // both the receiver and right-hand-side are believed not to be null. SetResultType(node, TypeWithState.Create(resultType, NullableFlowState.MaybeDefault)); _currentConditionalReceiverVisitResult = default; _lastConditionalAccessSlot = previousConditionalAccessSlot; void makeAndAdjustReceiverSlot(BoundExpression receiver) { var slot = MakeSlot(receiver); if (slot > -1) LearnFromNonNullTest(slot, ref State); // given `a?.b()`, when `a` is a nullable value type, // the conditional receiver for `?.b()` must be linked to `a.Value`, not to `a`. if (slot > 0 && receiver.Type?.IsNullableType() == true) slot = GetNullableOfTValueSlot(receiver.Type, slot, out _); _lastConditionalAccessSlot = slot; } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, out _); return null; } protected override BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; TypeWithState consequenceRValue; TypeWithState alternativeRValue; if (isRef) { TypeWithAnnotations consequenceLValue; TypeWithAnnotations alternativeLValue; (consequenceLValue, consequenceRValue) = visitConditionalRefOperand(consequenceState, originalConsequence); consequenceState = this.State; (alternativeLValue, alternativeRValue) = visitConditionalRefOperand(alternativeState, originalAlternative); Join(ref this.State, ref consequenceState); TypeSymbol? refResultType = node.Type?.SetUnknownNullabilityForReferenceTypes(); if (IsNullabilityMismatch(consequenceLValue, alternativeLValue)) { // l-value types must match ReportNullabilityMismatchInAssignment(node.Syntax, consequenceLValue, alternativeLValue); } else if (!node.HasErrors) { refResultType = consequenceRValue.Type!.MergeEquivalentTypes(alternativeRValue.Type, VarianceKind.None); } var lValueAnnotation = consequenceLValue.NullableAnnotation.EnsureCompatible(alternativeLValue.NullableAnnotation); var rValueState = consequenceRValue.State.Join(alternativeRValue.State); SetResult(node, TypeWithState.Create(refResultType, rValueState), TypeWithAnnotations.Create(refResultType, lValueAnnotation)); return null; } (var consequence, var consequenceConversion, consequenceRValue) = visitConditionalOperand(consequenceState, originalConsequence); var consequenceConditionalState = PossiblyConditionalState.Create(this); consequenceState = CloneAndUnsplit(ref consequenceConditionalState); var consequenceEndReachable = consequenceState.Reachable; (var alternative, var alternativeConversion, alternativeRValue) = visitConditionalOperand(alternativeState, originalAlternative); var alternativeConditionalState = PossiblyConditionalState.Create(this); alternativeState = CloneAndUnsplit(ref alternativeConditionalState); var alternativeEndReachable = alternativeState.Reachable; SetPossiblyConditionalState(in consequenceConditionalState); Join(ref alternativeConditionalState); TypeSymbol? resultType; bool wasTargetTyped = node is BoundConditionalOperator { WasTargetTyped: true }; if (node.HasErrors || wasTargetTyped) { resultType = null; } else { // Determine nested nullability using BestTypeInferrer. // If a branch is unreachable, we could use the nested nullability of the other // branch, but that requires using the nullability of the branch as it applies to the // target type. For instance, the result of the conditional in the following should // be `IEnumerable<object>` not `object[]`: // object[] a = ...; // IEnumerable<object?> b = ...; // var c = true ? a : b; BoundExpression consequencePlaceholder = CreatePlaceholderIfNecessary(consequence, consequenceRValue.ToTypeWithAnnotations(compilation)); BoundExpression alternativePlaceholder = CreatePlaceholderIfNecessary(alternative, alternativeRValue.ToTypeWithAnnotations(compilation)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(consequencePlaceholder, alternativePlaceholder, _conversions, out _, ref discardedUseSiteInfo); } resultType ??= node.Type?.SetUnknownNullabilityForReferenceTypes(); NullableFlowState resultState; if (!wasTargetTyped) { if (resultType is null) { // This can happen when we're inferring the return type of a lambda. For this case, we don't need to do any work, // the unconverted conditional operator can't contribute info. The conversion that should be on top of this // can add or remove nullability, and nested nodes aren't being publicly exposed by the semantic model. Debug.Assert(node is BoundUnconvertedConditionalOperator); Debug.Assert(_returnTypesOpt is not null); resultState = default; } else { var resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); TypeWithState convertedConsequenceResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalConsequence, consequence, consequenceConversion, resultTypeWithAnnotations, consequenceRValue, consequenceState, consequenceEndReachable); TypeWithState convertedAlternativeResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalAlternative, alternative, alternativeConversion, resultTypeWithAnnotations, alternativeRValue, alternativeState, alternativeEndReachable); resultState = convertedConsequenceResult.State.Join(convertedAlternativeResult.State); } } else { resultState = consequenceRValue.State.Join(alternativeRValue.State); ConditionalInfoForConversion.Add(node, ImmutableArray.Create( (consequenceState, consequenceRValue, consequenceEndReachable), (alternativeState, alternativeRValue, alternativeEndReachable))); } SetResultType(node, TypeWithState.Create(resultType, resultState)); return null; (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) { Conversion conversion; SetState(state); Debug.Assert(!isRef); BoundExpression operandNoConversion; (operandNoConversion, conversion) = RemoveConversion(operand, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(operand, operandNoConversion); Visit(operandNoConversion); return (operandNoConversion, conversion, ResultType); } (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) { SetState(state); Debug.Assert(isRef); TypeWithAnnotations lValueType = VisitLvalueWithAnnotations(operand); return (lValueType, ResultType); } } private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult( BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) { var savedState = this.State; this.State = state; bool previousDisabledDiagnostics = _disableDiagnostics; // If the node is not reachable, then we're only visiting to get // nullability information for the public API, and not to produce diagnostics. // Disable diagnostics, and return default for the resulting state // to indicate that warnings were suppressed. if (!isReachable) { _disableDiagnostics = true; } var resultType = VisitConversion( GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false); if (!isReachable) { resultType = default; _disableDiagnostics = previousDisabledDiagnostics; } this.State = savedState; return resultType; } private bool IsReachable() => this.IsConditionalState ? (this.StateWhenTrue.Reachable || this.StateWhenFalse.Reachable) : this.State.Reachable; /// <summary> /// Placeholders are bound expressions with type and state. /// But for typeless expressions (such as `null` or `(null, null)` we hold onto the original bound expression, /// as it will be useful for conversions from expression. /// </summary> private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) { return !type.HasType ? expr : new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); } public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) { var rvalueType = _currentConditionalReceiverVisitResult.RValueType.Type; if (rvalueType?.IsNullableType() == true) { rvalueType = rvalueType.GetNullableUnderlyingType(); } SetResultType(node, TypeWithState.Create(rvalueType, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitCall(BoundCall node) { // Note: we analyze even omitted calls TypeWithState receiverType = VisitCallReceiver(node); ReinferMethodAndVisitArguments(node, receiverType); return null; } private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType) { var method = node.Method; ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt; if (!receiverType.HasNullType) { // Update method based on inferred receiver type. method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } ImmutableArray<VisitArgumentResult> results; bool returnNotNull; (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); LearnFromEqualsMethod(method, node, receiverType, results); var returnState = GetReturnTypeWithState(method); if (returnNotNull) { returnState = returnState.WithNotNullState(); } SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray<VisitArgumentResult> results) { // easy out var parameterCount = method.ParameterCount; var arguments = node.Arguments; if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || method.MethodKind != MethodKind.Ordinary || method.ReturnType.SpecialType != SpecialType.System_Boolean || (method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__Equals).Name && method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__ReferenceEquals).Name && !anyOverriddenMethodHasExplicitImplementation(method))) { return; } var isStaticEqualsMethod = method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__EqualsObjectObject)) || method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals)); if (isStaticEqualsMethod || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_Collections_Generic_IEqualityComparer_T__Equals)) { Debug.Assert(arguments.Length == 2); learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); return; } var isObjectEqualsMethodOrOverride = method.GetLeastOverriddenMethod(accessingTypeOpt: null) .Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals)); if (node.ReceiverOpt is BoundExpression receiver && (isObjectEqualsMethodOrOverride || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_IEquatable_T__Equals))) { Debug.Assert(arguments.Length == 1); learnFromEqualsMethodArguments(receiver, receiverType, arguments[0], results[0].RValueType); return; } static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol method) { for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.IsExplicitInterfaceImplementation) { return true; } } return false; } static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol method, TypeSymbol? receiverType, WellKnownMember wellKnownMember) { var wellKnownMethod = (MethodSymbol?)compilation.GetWellKnownTypeMember(wellKnownMember); if (wellKnownMethod is null || receiverType is null) { return false; } var wellKnownType = wellKnownMethod.ContainingType; var parameterType = method.Parameters[0].TypeWithAnnotations; var constructedType = wellKnownType.Construct(ImmutableArray.Create(parameterType)); var constructedMethod = wellKnownMethod.AsMember(constructedType); // FindImplementationForInterfaceMember doesn't check if this method is itself the interface method we're looking for if (constructedMethod.Equals(method)) { return true; } // check whether 'method', when called on this receiver, is an implementation of 'constructedMethod'. for (var baseType = receiverType; baseType is object && method is object; baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var implementationMethod = baseType.FindImplementationForInterfaceMember(constructedMethod); if (implementationMethod is null) { // we know no base type will implement this interface member either return false; } if (implementationMethod.ContainingType.IsInterface) { // this method cannot be called directly from source because an interface can only explicitly implement a method from its base interface. return false; } // could be calling an override of a method that implements the interface method for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.Equals(implementationMethod)) { return true; } } // the Equals method being called isn't the method that implements the interface method in this type. // it could be a method that implements the interface on a base type, so check again with the base type of 'implementationMethod.ContainingType' // e.g. in this hierarchy: // class A -> B -> C -> D // method virtual B.Equals -> override D.Equals // // we would potentially check: // 1. D.Equals when called on D, then B.Equals when called on D // 2. B.Equals when called on C // 3. B.Equals when called on B // 4. give up when checking A, since B.Equals is not overriding anything in A // we know that implementationMethod.ContainingType is the same type or a base type of 'baseType', // and that the implementation method will be the same between 'baseType' and 'implementationMethod.ContainingType'. // we step through the intermediate bases in order to skip unnecessary override methods. while (!baseType.Equals(implementationMethod.ContainingType) && method is object) { if (baseType.Equals(method.ContainingType)) { // since we're about to move on to the base of 'method.ContainingType', // we know the implementation could only be an overridden method of 'method'. method = method.OverriddenMethod; } baseType = baseType.BaseTypeNoUseSiteDiagnostics; // the implementation method must be contained in this 'baseType' or one of its bases. Debug.Assert(baseType is object); } // now 'baseType == implementationMethod.ContainingType', so if 'method' is // contained in that same type we should advance 'method' one more time. if (method is object && baseType.Equals(method.ContainingType)) { method = method.OverriddenMethod; } } return false; } void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) { // comparing anything to a null literal gives maybe-null when true and not-null when false // comparing a maybe-null to a not-null gives us not-null when true, nothing learned when false if (left.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(right, ref StateWhenTrue); LearnFromNonNullTest(right, ref StateWhenFalse); } else if (right.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(left, ref StateWhenTrue); LearnFromNonNullTest(left, ref StateWhenFalse); } else if (leftType.MayBeNull && rightType.IsNotNull) { Split(); LearnFromNonNullTest(left, ref StateWhenTrue); } else if (rightType.MayBeNull && leftType.IsNotNull) { Split(); LearnFromNonNullTest(right, ref StateWhenTrue); } } } private bool IsCompareExchangeMethod(MethodSymbol? method) { if (method is null) { return false; } return method.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange), SymbolEqualityComparer.ConsiderEverything.CompareKind) || method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T), SymbolEqualityComparer.ConsiderEverything.CompareKind); } private readonly struct CompareExchangeInfo { public readonly ImmutableArray<BoundExpression> Arguments; public readonly ImmutableArray<VisitArgumentResult> Results; public readonly ImmutableArray<int> ArgsToParamsOpt; public CompareExchangeInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> results, ImmutableArray<int> argsToParamsOpt) { Arguments = arguments; Results = results; ArgsToParamsOpt = argsToParamsOpt; } public bool IsDefault => Arguments.IsDefault || Results.IsDefault; } private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) { Debug.Assert(!compareExchangeInfo.IsDefault); // In general a call to CompareExchange of the form: // // Interlocked.CompareExchange(ref location, value, comparand); // // will be analyzed similarly to the following: // // if (location == comparand) // { // location = value; // } if (compareExchangeInfo.Arguments.Length != 3) { // This can occur if CompareExchange has optional arguments. // Since none of the main runtimes have optional arguments, // we bail to avoid an exception but don't bother actually calculating the FlowState. return NullableFlowState.NotNull; } var argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; Debug.Assert(argsToParamsOpt is { IsDefault: true } or { Length: 3 }); var (comparandIndex, valueIndex, locationIndex) = argsToParamsOpt.IsDefault ? (2, 1, 0) : (argsToParamsOpt.IndexOf(2), argsToParamsOpt.IndexOf(1), argsToParamsOpt.IndexOf(0)); var comparand = compareExchangeInfo.Arguments[comparandIndex]; var valueFlowState = compareExchangeInfo.Results[valueIndex].RValueType.State; if (comparand.ConstantValue?.IsNull == true) { // If location contained a null, then the write `location = value` definitely occurred } else { var locationFlowState = compareExchangeInfo.Results[locationIndex].RValueType.State; // A write may have occurred valueFlowState = valueFlowState.Join(locationFlowState); } return valueFlowState; } private TypeWithState VisitCallReceiver(BoundCall node) { var receiverOpt = node.ReceiverOpt; TypeWithState receiverType = default; if (receiverOpt != null) { receiverType = VisitRvalueWithState(receiverOpt); // methods which are members of Nullable<T> (ex: ToString, GetHashCode) can be invoked on null receiver. // However, inherited methods (ex: GetType) are invoked on a boxed value (since base types are reference types) // and therefore in those cases nullable receivers should be checked for nullness. bool checkNullableValueType = false; var type = receiverType.Type; var method = node.Method; if (method.RequiresInstanceReceiver && type?.IsNullableType() == true && method.ContainingType.IsReferenceType) { checkNullableValueType = true; } else if (method.OriginalDefinition == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { // call to get_Value may not occur directly in source, but may be inserted as a result of premature lowering. // One example where we do it is foreach with nullables. // The reason is Dev10 compatibility (see: UnwrapCollectionExpressionIfNullable in ForEachLoopBinder.cs) // Regardless of the reasons, we know that the method does not tolerate nulls. checkNullableValueType = true; } // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType); } return receiverType; } private TypeWithState GetReturnTypeWithState(MethodSymbol method) { return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); } private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = symbol.GetFlowAnalysisAnnotations(); return annotations & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); } private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) return IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : parameter.FlowAnalysisAnnotations; } /// <summary> /// Fix a TypeWithAnnotations based on Allow/DisallowNull annotations prior to a conversion or assignment. /// Note this does not work for nullable value types, so an additional check with <see cref="CheckDisallowedNullAssignment"/> may be required. /// </summary> private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) { if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) { return declaredType.AsNotAnnotated(); } else if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) { return declaredType.AsAnnotated(); } return declaredType; } /// <summary> /// Update the null-state based on MaybeNull/NotNull /// </summary> private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } return typeWithState; } private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return declaredType.AsAnnotated(); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return declaredType.AsNotAnnotated(); } return declaredType; } // https://github.com/dotnet/roslyn/issues/29863 Record in the node whether type // arguments were implicit, to allow for cases where the syntax is not an // invocation (such as a synthesized call from a query interpretation). private static bool HasImplicitTypeArguments(BoundNode node) { if (node is BoundCollectionElementInitializer { AddMethod: { TypeArgumentsWithAnnotations: { IsEmpty: false } } }) { return true; } if (node is BoundForEachStatement { EnumeratorInfoOpt: { GetEnumeratorInfo: { Method: { TypeArgumentsWithAnnotations: { IsEmpty: false } } } } }) { return true; } var syntax = node.Syntax; if (syntax.Kind() != SyntaxKind.InvocationExpression) { // Unexpected syntax kind. return false; } return HasImplicitTypeArguments(((InvocationExpressionSyntax)syntax).Expression); } private static bool HasImplicitTypeArguments(SyntaxNode syntax) { var nameSyntax = Binder.GetNameSyntax(syntax, out _); if (nameSyntax == null) { // Unexpected syntax kind. return false; } nameSyntax = nameSyntax.GetUnqualifiedName(); return nameSyntax.Kind() != SyntaxKind.GenericName; } protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { // Callers should be using VisitArguments overload below. throw ExceptionUtilities.Unreachable; } private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol? method, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray<VisitArgumentResult> VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, PropertySymbol? property, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// <summary> /// If you pass in a method symbol, its type arguments will be re-inferred and the re-inferred method will be returned. /// </summary> private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) { Debug.Assert(!arguments.IsDefault); bool shouldReturnNotNull = false; (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // Re-infer method type parameters if (method?.IsGenericMethod == true) { if (HasImplicitTypeArguments(node)) { method = InferMethodTypeArguments(method, GetArgumentsForMethodTypeInference(results, argumentsNoConversions), refKindsOpt, argsToParamsOpt, expanded); parametersOpt = method.Parameters; } if (ConstraintsHelper.RequiresChecking(method)) { var syntax = node.Syntax; CheckMethodConstraints( syntax switch { InvocationExpressionSyntax { Expression: var expression } => expression, ForEachStatementSyntax { Expression: var expression } => expression, _ => syntax }, method); } } bool parameterHasNotNullIfNotNull = !IsAnalyzingAttribute && !parametersOpt.IsDefault && parametersOpt.Any(p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; if (!parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentNoConversion; if (argument is not BoundConversion && argumentNoConversion is BoundLambda lambda) { Debug.Assert(node.HasErrors); Debug.Assert((object)argument == argumentNoConversion); // 'VisitConversion' only visits a lambda when the lambda has an AnonymousFunction conversion. // This lambda doesn't have a conversion, so we need to visit it here. VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); continue; } (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { // If this assert fails, we are missing necessary info to visit the // conversion of a target typed conditional or switch. Debug.Assert(argumentNoConversion is not (BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) && _conditionalInfoForConversionOpt?.ContainsKey(argumentNoConversion) is null or false); // If this assert fails, it means we failed to visit a lambda for error recovery above. Debug.Assert(argumentNoConversion is not BoundLambda); continue; } // We disable diagnostics when: // 1. the containing call has errors (to reduce cascading diagnostics) // 2. on implicit default arguments (since that's really only an issue with the declaration) var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= node.HasErrors || defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } if (node is BoundCall { Method: { OriginalDefinition: LocalFunctionSymbol localFunction } }) { VisitLocalFunctionUse(localFunction); } if (!node.HasErrors && !parametersOpt.IsDefault) { // For CompareExchange method we need more context to determine the state of outbound assignment CompareExchangeInfo compareExchangeInfo = IsCompareExchangeMethod(method) ? new CompareExchangeInfo(arguments, results, argsToParamsOpt) : default; // Visit outbound assignments and post-conditions // Note: the state may get split in this step for (int i = 0; i < arguments.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } VisitArgumentOutboundAssignmentsAndPostConditions( arguments[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], notNullParametersBuilder, (!compareExchangeInfo.IsDefault && parameter.Ordinal == 0) ? compareExchangeInfo : default); } } else { for (int i = 0; i < arguments.Length; i++) { // We can hit this case when dynamic methods are involved, or when there are errors. In either case we have no information, // so just assume that the conversions have the same nullability as the underlying result var argument = arguments[i]; var result = results[i]; var argumentNoConversion = argumentsNoConversions[i]; TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(argument.Type, result.RValueType.State), argument as BoundConversion, argumentNoConversion); } } if (!IsAnalyzingAttribute && method is object && (method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) { SetUnreachable(); } notNullParametersBuilder?.Free(); return (method, results, shouldReturnNotNull); } private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) { if (method is null) { return; } int receiverSlot = method.IsStatic ? 0 : receiverOpt is null ? -1 : MakeSlot(receiverOpt); if (receiverSlot < 0) { return; } ApplyMemberPostConditions(receiverSlot, method); } private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) { Debug.Assert(receiverSlot >= 0); do { var type = method.ContainingType; var notNullMembers = method.NotNullMembers; var notNullWhenTrueMembers = method.NotNullWhenTrueMembers; var notNullWhenFalseMembers = method.NotNullWhenFalseMembers; if (IsConditionalState) { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenFalse); } else { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref State); } if (!notNullWhenTrueMembers.IsEmpty || !notNullWhenFalseMembers.IsEmpty) { Split(); applyMemberPostConditions(receiverSlot, type, notNullWhenTrueMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullWhenFalseMembers, ref StateWhenFalse); } method = method.OverriddenMethod; } while (method != null); void applyMemberPostConditions(int receiverSlot, TypeSymbol type, ImmutableArray<string> members, ref LocalState state) { if (members.IsEmpty) { return; } foreach (var memberName in members) { markMembersAsNotNull(receiverSlot, type, memberName, ref state); } } void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, ref LocalState state) { foreach (Symbol member in type.GetMembers(memberName)) { if (member.IsStatic) { receiverSlot = 0; } switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (GetOrCreateSlot(member, receiverSlot) is int memberSlot && memberSlot > 0) { state[memberSlot] = NullableFlowState.NotNull; } break; case SymbolKind.Event: case SymbolKind.Method: break; } } } } private ImmutableArray<VisitArgumentResult> VisitArgumentsEvaluate( SyntaxNode syntax, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var visitedParameters = PooledHashSet<ParameterSymbol?>.GetInstance(); var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); return resultsBuilder.ToImmutableAndFree(); } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) { Debug.Assert(!IsConditionalState); var savedState = (argument.Kind == BoundKind.Lambda) ? this.State.Clone() : default(Optional<LocalState>); // Note: DoesNotReturnIf is ineffective on ref/out parameters switch (refKind) { case RefKind.Ref: Visit(argument); Unsplit(); break; case RefKind.None: case RefKind.In: switch (annotations & (FlowAnalysisAnnotations.DoesNotReturnIfTrue | FlowAnalysisAnnotations.DoesNotReturnIfFalse)) { case FlowAnalysisAnnotations.DoesNotReturnIfTrue: Visit(argument); if (IsConditionalState) { SetState(StateWhenFalse); } break; case FlowAnalysisAnnotations.DoesNotReturnIfFalse: Visit(argument); if (IsConditionalState) { SetState(StateWhenTrue); } break; default: VisitRvalue(argument); break; } break; case RefKind.Out: // As far as we can tell, there is no scenario relevant to nullability analysis // where splitting an L-value (for instance with a ref conditional) would affect the result. Visit(argument); // We'll want to use the l-value type, rather than the result type, for method re-inference UseLvalueOnly(argument); break; } Debug.Assert(!IsConditionalState); return new VisitArgumentResult(_visitResult, savedState); } /// <summary> /// Verifies that an argument's nullability is compatible with its parameter's on the way in. /// </summary> private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, bool extensionMethodThisArgument) { Debug.Assert(!this.IsConditionalState); // Note: we allow for some variance in `in` and `out` cases. Unlike in binding, we're not // limited by CLR constraints. var resultType = result.RValueType; switch (refKind) { case RefKind.None: case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) { var argumentResultType = resultType.Type; conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false); if (!conversion.Exists && !argumentNoConversion.IsSuppressed) { Debug.Assert(argumentResultType is not null); ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); } } var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, conversion: conversion, targetTypeWithNullability: ApplyLValueAnnotations(parameterType, parameterAnnotations), operandType: resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter, extensionMethodThisArgument: extensionMethodThisArgument, stateForLambda: result.StateForLambda); // If the parameter has annotations, we perform an additional check for nullable value types if (CheckDisallowedNullAssignment(stateAfterConversion, parameterAnnotations, argumentNoConversion.Syntax.Location)) { LearnFromNonNullTest(argumentNoConversion, ref State); } SetResultType(argumentNoConversion, stateAfterConversion, updateAnalyzedNullability: false); } break; case RefKind.Ref: if (!argumentNoConversion.IsSuppressed) { var lvalueResultType = result.LValueType; if (IsNullabilityMismatch(lvalueResultType.Type, parameterType.Type)) { // declared types must match, ignoring top-level nullability ReportNullabilityMismatchInRefArgument(argumentNoConversion, argumentType: lvalueResultType.Type, parameter, parameterType.Type); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), resultType, useLegacyWarnings: false); // If the parameter has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, argumentNoConversion.Syntax.Location); } } break; case RefKind.Out: break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } Debug.Assert(!this.IsConditionalState); } /// <summary>Returns <see langword="true"/> if this is an assignment forbidden by DisallowNullAttribute, otherwise <see langword="false"/>.</summary> private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, Location location, BoundExpression? boundValueOpt = null) { if (boundValueOpt is { WasCompilerGenerated: true }) { // We need to skip `return backingField;` in auto-prop getters return false; } // We do this extra check for types whose non-nullable version cannot be represented if (IsDisallowedNullAssignment(state, annotations)) { ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, location); return true; } return false; } private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) { return ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) && hasNoNonNullableCounterpart(valueState.Type) && valueState.MayBeNull; static bool hasNoNonNullableCounterpart(TypeSymbol? type) { if (type is null) { return false; } // Some types that could receive a maybe-null value have a NotNull counterpart: // [NotNull]string? -> string // [NotNull]string -> string // [NotNull]TClass -> TClass // [NotNull]TClass? -> TClass // // While others don't: // [NotNull]int? -> X // [NotNull]TNullable -> X // [NotNull]TStruct? -> X // [NotNull]TOpen -> X return (type.Kind == SymbolKind.TypeParameter && !type.IsReferenceType) || type.IsNullableTypeOrTypeParameter(); } } /// <summary> /// Verifies that outbound assignments (from parameter to argument) are safe and /// tracks those assignments (or learns from post-condition attributes) /// </summary> private void VisitArgumentOutboundAssignmentsAndPostConditions( BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) { // Note: the state may be conditional if a previous argument involved a conditional post-condition // The WhenTrue/False states correspond to the invocation returning true/false switch (refKind) { case RefKind.None: case RefKind.In: { // learn from post-conditions [Maybe/NotNull, Maybe/NotNullWhen] without using an assignment learnFromPostConditions(argument, parameterType, parameterAnnotations); } break; case RefKind.Ref: { // assign from a fictional value from the parameter to the argument. parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); if (!compareExchangeInfoOpt.IsDefault) { var adjustedState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); parameterWithState = TypeWithState.Create(parameterType.Type, adjustedState); } var parameterValue = new BoundParameter(argument.Syntax, parameter); var lValueType = result.LValueType; trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // check whether parameter would unsafely let a null out in the worse case if (!argument.IsSuppressed) { var leftAnnotations = GetLValueAnnotations(argument); ReportNullableAssignmentIfNecessary( parameterValue, targetType: ApplyLValueAnnotations(lValueType, leftAnnotations), valueType: applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations), UseLegacyWarnings(argument, result.LValueType)); } } break; case RefKind.Out: { // compute the fictional parameter state parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); // Adjust parameter state if MaybeNull or MaybeNullWhen are present (for `var` type and for assignment warnings) var worstCaseParameterWithState = applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations); var declaredType = result.LValueType; var leftAnnotations = GetLValueAnnotations(argument); var lValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType) { var varType = worstCaseParameterWithState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local.LocalSymbol, varType); lValueType = varType; } else if (argument is BoundDiscardExpression discard) { SetAnalyzedNullability(discard, new VisitResult(parameterWithState, parameterWithState.ToTypeWithAnnotations(compilation)), isLvalue: true); } // track state by assigning from a fictional value from the parameter to the argument. var parameterValue = new BoundParameter(argument.Syntax, parameter); // If the argument type has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(parameterWithState, leftAnnotations, argument.Syntax.Location); AdjustSetValue(argument, ref parameterWithState); trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // report warnings if parameter would unsafely let a null out in the worst case if (!argument.IsSuppressed) { ReportNullableAssignmentIfNecessary(parameterValue, lValueType, worstCaseParameterWithState, UseLegacyWarnings(argument, result.LValueType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, lValueType.Type, ref discardedUseSiteInfo)) { ReportNullabilityMismatchInArgument(argument.Syntax, lValueType.Type, parameter, parameterType.Type, forOutput: true); } } } break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations parameterAnnotations, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, ParameterSymbol parameter) { if (!IsAnalyzingAttribute && notNullParametersOpt is object) { var notNullIfParameterNotNull = parameter.NotNullIfParameterNotNull; if (!notNullIfParameterNotNull.IsEmpty) { foreach (var notNullParameter in notNullParametersOpt) { if (notNullIfParameterNotNull.Contains(notNullParameter.Name)) { return FlowAnalysisAnnotations.NotNull; } } } } return parameterAnnotations; } void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations lValueType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations parameterAnnotations) { if (!IsConditionalState && !hasConditionalPostCondition(parameterAnnotations)) { TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); } else { Split(); var originalWhenFalse = StateWhenFalse.Clone(); SetState(StateWhenTrue); // Note: the suppression applies over the post-condition attributes TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); var newWhenTrue = State.Clone(); SetState(originalWhenFalse); TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); SetConditionalState(newWhenTrue, whenFalse: State); } } static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) { return (((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0)) || (((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0)); } static TypeWithState applyPostConditionsUnconditionally(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNull return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenTrue(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && !(maybeNullWhenFalse && notNullWhenTrue)) { // [MaybeNull, NotNullWhen(true)] means [MaybeNullWhen(false)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenTrue) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenFalse(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenFalse && !(maybeNullWhenTrue && notNullWhenFalse)) { // [MaybeNull, NotNullWhen(false)] means [MaybeNullWhen(true)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenFalse) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } void learnFromPostConditions(BoundExpression argument, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { // Note: NotNull = NotNullWhen(true) + NotNullWhen(false) bool notNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool notNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; // Note: MaybeNull = MaybeNullWhen(true) + MaybeNullWhen(false) bool maybeNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && maybeNullWhenFalse && !IsConditionalState && !(notNullWhenTrue && notNullWhenFalse)) { LearnFromNullTest(argument, ref State); } else if (notNullWhenTrue && notNullWhenFalse && !IsConditionalState && !(maybeNullWhenTrue || maybeNullWhenFalse)) { LearnFromNonNullTest(argument, ref State); } else if (notNullWhenTrue || notNullWhenFalse || maybeNullWhenTrue || maybeNullWhenFalse) { Split(); if (notNullWhenTrue) { LearnFromNonNullTest(argument, ref StateWhenTrue); } if (notNullWhenFalse) { LearnFromNonNullTest(argument, ref StateWhenFalse); } if (maybeNullWhenTrue) { LearnFromNullTest(argument, ref StateWhenTrue); } if (maybeNullWhenFalse) { LearnFromNullTest(argument, ref StateWhenFalse); } } } } private (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) RemoveArgumentConversions( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { int n = arguments.Length; var conversions = default(ImmutableArray<Conversion>); if (n > 0) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n); bool includedConversion = false; for (int i = 0; i < n; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); var argument = arguments[i]; var conversion = Conversion.Identity; if (refKind == RefKind.None) { var before = argument; (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false); if (argument != before) { SnapshotWalkerThroughConversionGroup(before, argument); includedConversion = true; } } argumentsBuilder.Add(argument); conversionsBuilder.Add(conversion); } if (includedConversion) { arguments = argumentsBuilder.ToImmutable(); conversions = conversionsBuilder.ToImmutable(); } argumentsBuilder.Free(); conversionsBuilder.Free(); } return (arguments, conversions); } private static VariableState GetVariableState(Variables variables, LocalState localState) { Debug.Assert(variables.Id == localState.Id); return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); } private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { if (parametersOpt.IsDefault) { return default; } var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); return default; } var type = parameter.TypeWithAnnotations; if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); } return (parameter, type, GetParameterAnnotations(parameter), isExpandedParamsArgument: false); } private MethodSymbol InferMethodTypeArguments( MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { Debug.Assert(method.IsGenericMethod); // https://github.com/dotnet/roslyn/issues/27961 OverloadResolution.IsMemberApplicableInNormalForm and // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here. var definition = method.ConstructedFrom; var refKinds = ArrayBuilder<RefKind>.GetInstance(); if (argumentRefKindsOpt != null) { refKinds.AddRange(argumentRefKindsOpt); } // https://github.com/dotnet/roslyn/issues/27961 Do we really need OverloadResolution.GetEffectiveParameterTypes? // Aren't we doing roughly the same calculations in GetCorrespondingParameter? OverloadResolution.GetEffectiveParameterTypes( definition, arguments.Length, argsToParamsOpt, refKinds, isMethodGroupConversion: false, // https://github.com/dotnet/roslyn/issues/27961 `allowRefOmittedArguments` should be // false for constructors and several other cases (see Binder use). Should we // capture the original value in the BoundCall? allowRefOmittedArguments: true, binder: _binder, expanded: expanded, parameterTypes: out ImmutableArray<TypeWithAnnotations> parameterTypes, parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds); refKinds.Free(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var result = MethodTypeInferrer.Infer( _binder, _conversions, definition.TypeParameters, definition.ContainingType, parameterTypes, parameterRefKinds, arguments, ref discardedUseSiteInfo, new MethodInferenceExtensions(this)); if (!result.Success) { return method; } return definition.Construct(result.InferredTypeArguments); } private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions { private readonly NullableWalker _walker; internal MethodInferenceExtensions(NullableWalker walker) { _walker = walker; } internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); } /// <summary> /// Return top-level nullability for the expression. This method should be called on a limited /// set of expressions only. It should not be called on expressions tracked by flow analysis /// other than <see cref="BoundKind.ExpressionWithNullability"/> which is an expression /// specifically created in NullableWalker to represent the flow analysis state. /// </summary> private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) { switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Literal: return expr.ConstantValue == ConstantValue.NotAvailable || !expr.ConstantValue.IsNull || expr.IsSuppressed ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: return NullableAnnotation.NotAnnotated; default: Debug.Assert(false); // unexpected value return NullableAnnotation.Oblivious; } } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out TypeWithState receiverType)) { if (!method.IsStatic) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } } return method.ReturnTypeWithAnnotations; } } private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<BoundExpression> arguments) { // https://github.com/dotnet/roslyn/issues/27961 MethodTypeInferrer.Infer relies // on the BoundExpressions for tuple element types and method groups. // By using a generic BoundValuePlaceholder, we're losing inference in those cases. // https://github.com/dotnet/roslyn/issues/27961 Inference should be based on // unconverted arguments. Consider cases such as `default`, lambdas, tuples. int n = argumentResults.Length; var builder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var visitArgumentResult = argumentResults[i]; var lambdaState = visitArgumentResult.StateForLambda; // Note: for `out` arguments, the argument result contains the declaration type (see `VisitArgumentEvaluate`) var argumentResult = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResult, lambdaState)); } return builder.ToImmutableAndFree(); BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations argumentType, Optional<LocalState> lambdaState) { if (argument.Kind == BoundKind.Lambda) { Debug.Assert(lambdaState.HasValue); // MethodTypeInferrer must infer nullability for lambdas based on the nullability // from flow analysis rather than the declared nullability. To allow that, we need // to re-bind lambdas in MethodTypeInferrer. return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); } if (!argumentType.HasType) { return argument; } if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } or BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) { // target-typed contexts don't contribute to nullability return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, type: null); } return new BoundExpressionWithNullability(argument.Syntax, argument, argumentType.NullableAnnotation, argumentType.Type); } static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) { return expr.UnboundLambda.WithNullableState(variableState); } } private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) { if (_disableDiagnostics) { return; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var nullabilityBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), diagnosticsBuilder, nullabilityBuilder, ref useSiteDiagnosticsBuilder); foreach (var pair in nullabilityBuilder) { if (pair.UseSiteInfo.DiagnosticInfo is object) { Diagnostics.Add(pair.UseSiteInfo.DiagnosticInfo, syntax.Location); } } useSiteDiagnosticsBuilder?.Free(); nullabilityBuilder.Free(); diagnosticsBuilder.Free(); } /// <summary> /// Returns the expression without the top-most conversion plus the conversion. /// If the expression is not a conversion, returns the original expression plus /// the Identity conversion. If `includeExplicitConversions` is true, implicit and /// explicit conversions are considered. If `includeExplicitConversions` is false /// only implicit conversions are considered and if the expression is an explicit /// conversion, the expression is returned as is, with the Identity conversion. /// (Currently, the only visit method that passes `includeExplicitConversions: true` /// is VisitConversion. All other callers are handling implicit conversions only.) /// </summary> private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) { ConversionGroup? group = null; while (true) { if (expr.Kind != BoundKind.Conversion) { break; } var conversion = (BoundConversion)expr; if (group != conversion.ConversionGroupOpt && group != null) { // E.g.: (C)(B)a break; } group = conversion.ConversionGroupOpt; Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group. if (!includeExplicitConversions && group?.IsExplicitConversion == true) { return (expr, Conversion.Identity); } expr = conversion.Operand; if (group == null) { // Ungrouped conversion should not be followed by another ungrouped // conversion. Otherwise, the conversions should have been grouped. // https://github.com/dotnet/roslyn/issues/34919 This assertion does not always hold true for // enum initializers //Debug.Assert(expr.Kind != BoundKind.Conversion || // ((BoundConversion)expr).ConversionGroupOpt != null || // ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion); return (expr, conversion.Conversion); } } return (expr, group?.Conversion ?? Conversion.Identity); } // See Binder.BindNullCoalescingOperator for initial binding. private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false); bool canConvertNestedNullability = conversion.Exists; if (!canConvertNestedNullability && reportMismatch && !sourceExpression.IsSuppressed) { ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); } return conversion; } private static Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool useExpression = sourceType is null || UseExpressionForConversion(sourceExpression); if (extensionMethodThisArgument) { return conversions.ClassifyImplicitExtensionMethodThisArgConversion( useExpression ? sourceExpression : null, sourceType, destinationType, ref discardedUseSiteInfo); } return useExpression ? (fromExplicitCast ? conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo)); } /// <summary> /// Returns true if the expression should be used as the source when calculating /// a conversion from this expression, rather than using the type (with nullability) /// calculated by visiting this expression. Typically, that means expressions that /// do not have an explicit type but there are several other cases as well. /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.) /// </summary> private static bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) { if (value is null) { return false; } if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null) { return true; } switch (value.Kind) { case BoundKind.InterpolatedString: return true; default: return false; } } /// <summary> /// Adjust declared type based on inferred nullability at the point of reference. /// </summary> private TypeWithState GetAdjustedResult(TypeWithState type, int slot) { if (this.State.HasValue(slot)) { NullableFlowState state = this.State[slot]; return TypeWithState.Create(type.Type, state); } return type; } /// <summary> /// Gets the corresponding member for a symbol from initial binding to match an updated receiver type in NullableWalker. /// For instance, this will map from List&lt;string~&gt;.Add(string~) to List&lt;string?&gt;.Add(string?) in the following example: /// <example> /// string s = null; /// var list = new[] { s }.ToList(); /// list.Add(null); /// </example> /// </summary> private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) { Debug.Assert((object)symbol != null); var containingType = type as NamedTypeSymbol; if (containingType is null || containingType.IsErrorType() || symbol is ErrorMethodSymbol) { return symbol; } if (symbol.Kind == SymbolKind.Method) { if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { // https://github.com/dotnet/roslyn/issues/27233 Handle type substitution for local functions. return symbol; } } if (symbol is TupleElementFieldSymbol or TupleErrorFieldSymbol) { return symbol.SymbolAsMember(containingType); } var symbolContainer = symbol.ContainingType; if (symbolContainer.IsAnonymousType) { int? memberIndex = symbol.Kind == SymbolKind.Property ? symbol.MemberIndexOpt : null; if (!memberIndex.HasValue) { return symbol; } return AnonymousTypeManager.GetAnonymousTypeProperty(containingType, memberIndex.GetValueOrDefault()); } if (!symbolContainer.IsGenericType) { Debug.Assert(symbol.ContainingType.IsDefinition); return symbol; } if (!containingType.IsGenericType) { return symbol; } if (symbolContainer.IsInterface) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } foreach (var @interface in containingType.AllInterfacesNoUseSiteDiagnostics) { if (tryAsMemberOfSingleType(@interface, out result)) { return result; } } } else { while (true) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } containingType = containingType.BaseTypeNoUseSiteDiagnostics; if ((object)containingType == null) { break; } } } Debug.Assert(false); // If this assert fails, add an appropriate test. return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) { if (!singleType.Equals(symbolContainer, TypeCompareKind.AllIgnoreOptions)) { result = null; return false; } var symbolDef = symbol.OriginalDefinition; result = symbolDef.SymbolAsMember(singleType); if (result is MethodSymbol resultMethod && resultMethod.IsGenericMethod) { result = resultMethod.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); } return true; } } public override BoundNode? VisitConversion(BoundConversion node) { // https://github.com/dotnet/roslyn/issues/35732: Assert VisitConversion is only used for explicit conversions. //Debug.Assert(node.ExplicitCastInCode); //Debug.Assert(node.ConversionGroupOpt != null); //Debug.Assert(node.ConversionGroupOpt.ExplicitType.HasType); TypeWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(node.Type); Debug.Assert(targetType.HasType); (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true); SnapshotWalkerThroughConversionGroup(node, operand); TypeWithState operandType = VisitRvalueWithState(operand); SetResultType(node, VisitConversion( node, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: fromExplicitCast, useLegacyWarnings: fromExplicitCast, AssignmentKind.Assignment, reportTopLevelWarnings: fromExplicitCast, reportRemainingWarnings: true, trackMembers: true)); return null; } /// <summary> /// Visit an expression. If an explicit target type is provided, the expression is converted /// to that type. This method should be called whenever an expression may contain /// an implicit conversion, even if that conversion was omitted from the bound tree, /// so the conversion can be re-classified with nullability. /// </summary> private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) { if (!targetTypeOpt.HasType) { return VisitRvalueWithState(expr); } (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); // If an explicit conversion was used in place of an implicit conversion, the explicit // conversion was created by initial binding after reporting "error CS0266: // Cannot implicitly convert type '...' to '...'. An explicit conversion exists ...". // Since an error was reported, we don't need to report nested warnings as well. bool reportNestedWarnings = !conversion.IsExplicit; var resultType = VisitConversion( GetConversionIfApplicable(expr, operand), operand, conversion, targetTypeOpt, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: useLegacyWarnings, assignmentKind, reportTopLevelWarnings: true, reportRemainingWarnings: reportNestedWarnings, trackMembers: trackMembers); return resultType; } private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) { if (nullableTypeOpt?.IsNullableType() == true && underlyingTypeOpt?.IsNullableType() == false) { var typeArg = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); if (typeArg.Type.Equals(underlyingTypeOpt, TypeCompareKind.AllIgnoreOptions)) { underlyingTypeWithAnnotations = typeArg; return true; } } underlyingTypeWithAnnotations = default; return false; } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { VisitTupleExpression(node); return null; } public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { Debug.Assert(!IsConditionalState); var savedState = this.State.Clone(); // Visit the source tuple so that the semantic model can correctly report nullability for it // Disable diagnostics, as we don't want to duplicate any that are produced by visiting the converted literal below VisitWithoutDiagnostics(node.SourceTuple); this.SetState(savedState); VisitTupleExpression(node); return null; } private void VisitTupleExpression(BoundTupleExpression node) { var arguments = node.Arguments; ImmutableArray<TypeWithState> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithState(a), this); ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations = elementTypes.SelectAsArray(a => a.ToTypeWithAnnotations(compilation)); var tupleOpt = (NamedTypeSymbol?)node.Type; if (tupleOpt is null) { SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); } else { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; TrackNullableStateOfTupleElements(slot, tupleOpt, arguments, elementTypes, argsToParamsOpt: default, useRestField: false); } tupleOpt = tupleOpt.WithElementTypes(elementTypesWithAnnotations); if (!_disableDiagnostics) { var locations = tupleOpt.TupleElements.SelectAsArray((element, location) => element.Locations.FirstOrDefault() ?? location, node.Syntax.Location); tupleOpt.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, diagnostics: null), typeSyntax: node.Syntax, locations, nullabilityDiagnosticsOpt: new BindingDiagnosticBag(Diagnostics)); } SetResultType(node, TypeWithState.Create(tupleOpt, NullableFlowState.NotNull)); } } /// <summary> /// Set the nullability of tuple elements for tuples at the point of construction. /// If <paramref name="useRestField"/> is true, the tuple was constructed with an explicit /// 'new ValueTuple' call, in which case the 8-th element, if any, represents the 'Rest' field. /// </summary> private void TrackNullableStateOfTupleElements( int slot, NamedTypeSymbol tupleType, ImmutableArray<BoundExpression> values, ImmutableArray<TypeWithState> types, ImmutableArray<int> argsToParamsOpt, bool useRestField) { Debug.Assert(tupleType.IsTupleType); Debug.Assert(values.Length == types.Length); Debug.Assert(values.Length == (useRestField ? Math.Min(tupleType.TupleElements.Length, NamedTypeSymbol.ValueTupleRestPosition) : tupleType.TupleElements.Length)); if (slot > 0) { var tupleElements = tupleType.TupleElements; int n = values.Length; if (useRestField) { n = Math.Min(n, NamedTypeSymbol.ValueTupleRestPosition - 1); } for (int i = 0; i < n; i++) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(i); trackState(values[argOrdinal], tupleElements[i], types[argOrdinal]); } if (useRestField && values.Length == NamedTypeSymbol.ValueTupleRestPosition && tupleType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() is FieldSymbol restField) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(NamedTypeSymbol.ValueTupleRestPosition - 1); trackState(values[argOrdinal], restField, types[argOrdinal]); } } void trackState(BoundExpression value, FieldSymbol field, TypeWithState valueType) { int targetSlot = GetOrCreateSlot(field, slot); TrackNullableStateForAssignment(value, field.TypeWithAnnotations, targetSlot, valueType, MakeSlot(value)); } int GetArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) { var index = argsToParamsOpt.IsDefault ? parameterOrdinal : argsToParamsOpt.IndexOf(parameterOrdinal); Debug.Assert(index != -1); return index; } } private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) { Debug.Assert(containingType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T); Debug.Assert(containingSlot > 0); Debug.Assert(valueSlot > 0); int targetSlot = GetNullableOfTValueSlot(containingType, containingSlot, out Symbol? symbol); if (targetSlot > 0) { TrackNullableStateForAssignment(value, symbol!.GetTypeOrReturnType(), targetSlot, valueType, valueSlot); } } private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) { Debug.Assert(conversion.Kind == ConversionKind.ImplicitTuple || conversion.Kind == ConversionKind.ExplicitTuple); Debug.Assert(slot > 0); Debug.Assert(valueSlot > 0); var valueTuple = operandType as NamedTypeSymbol; if (valueTuple is null || !valueTuple.IsTupleType) { return; } var conversions = conversion.UnderlyingConversions; var targetElements = ((NamedTypeSymbol)targetType).TupleElements; var valueElements = valueTuple.TupleElements; int n = valueElements.Length; for (int i = 0; i < n; i++) { trackConvertedValue(targetElements[i], conversions[i], valueElements[i]); } void trackConvertedValue(FieldSymbol targetField, Conversion conversion, FieldSymbol valueField) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: case ConversionKind.Boxing: case ConversionKind.Unboxing: InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, skipSlot: slot); break; case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion, targetField.Type, valueField.Type, targetFieldSlot, valueFieldSlot, assignmentKind, parameterOpt, reportWarnings); } } } break; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out _)) { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfNullableValue(targetFieldSlot, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), valueFieldSlot); } } } break; case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: { var convertedType = VisitUserDefinedConversion( conversionOpt, convertedNode, conversion, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: reportWarnings, diagnosticLocation: (conversionOpt ?? convertedNode).Syntax.GetLocation()); int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = convertedType.State; } } break; default: break; } } } public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { base.VisitTupleBinaryOperator(node); SetNotNullResult(node); return null; } private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceInvokeMethod, new BindingDiagnosticBag(Diagnostics), reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: (targetType, location), invokedAsExtensionMethod: invokedAsExtensionMethod); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, new FormattedSymbol(sourceInvokeMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); } } private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, UnboundLambda unboundLambda) { if (!unboundLambda.HasExplicitlyTypedParameterList) { return; } var invoke = delegateType?.DelegateInvokeMethod; if (invoke is null) { return; } Debug.Assert(delegateType is object); if (unboundLambda.HasExplicitReturnType(out _, out var returnType) && IsNullabilityMismatch(invoke.ReturnTypeWithAnnotations, returnType, requireIdentity: true)) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount); for (int i = 0; i < count; i++) { var invokeParameter = invoke.Parameters[i]; // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding. // Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability. // (Compare with method group conversions which pass `requireIdentity: false`.) if (IsNullabilityMismatch(invokeParameter.TypeWithAnnotations, unboundLambda.ParameterTypeWithAnnotations(i), requireIdentity: true)) { // Should the warning be reported using location of specific lambda parameter? ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(i), unboundLambda.MessageID.Localize(), delegateType); } } } private bool IsNullabilityMismatch(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity)) { return true; } if (requireIdentity) { return IsNullabilityMismatch(source, destination); } var sourceType = source.Type; var destinationType = destination.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo).Exists; } private bool HasTopLevelNullabilityConversion(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { return requireIdentity ? _conversions.HasTopLevelNullabilityIdentityConversion(source, destination) : _conversions.HasTopLevelNullabilityImplicitConversion(source, destination); } /// <summary> /// Gets the conversion node for passing to <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional{LocalState}, bool, Location)"/>, /// if one should be passed. /// </summary> private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) { Debug.Assert(conversionOpt is null || convertedNode == conversionOpt // Note that convertedNode itself can be a BoundConversion, so we do this check explicitly // because the below calls to RemoveConversion could potentially strip that conversion. || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: false).expression || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: true).expression); return conversionOpt == convertedNode ? null : (BoundConversion?)conversionOpt; } /// <summary> /// Apply the conversion to the type of the operand and return the resulting type. /// If the operand does not have an explicit type, the operand expression is used. /// </summary> /// <param name="checkConversion"> /// If <see langword="true"/>, the incoming conversion is assumed to be from binding /// and will be re-calculated, this time considering nullability. /// Note that the conversion calculation considers nested nullability only. /// The caller is responsible for checking the top-level nullability of /// the type returned by this method. /// </param> /// <param name="trackMembers"> /// If <see langword="true"/>, the nullability of any members of the operand /// will be copied to the converted result when possible. /// </param> /// <param name="useLegacyWarnings"> /// If <see langword="true"/>, indicates that the "non-safety" diagnostic <see cref="ErrorCode.WRN_ConvertingNullableToNonNullable"/> /// should be given for an invalid conversion. /// </param> private TypeWithState VisitConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional<LocalState> stateForLambda = default, bool trackMembers = false, Location? diagnosticLocationOpt = null) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != null); NullableFlowState resultState = NullableFlowState.NotNull; bool canConvertNestedNullability = true; bool isSuppressed = false; diagnosticLocationOpt ??= (conversionOpt ?? conversionOperand).Syntax.GetLocation(); if (conversionOperand.IsSuppressed == true) { reportTopLevelWarnings = false; reportRemainingWarnings = false; isSuppressed = true; } #nullable disable TypeSymbol targetType = targetTypeWithNullability.Type; switch (conversion.Kind) { case ConversionKind.MethodGroup: { var group = conversionOperand as BoundMethodGroup; var (invokeSignature, parameters) = getDelegateOrFunctionPointerInfo(targetType); var method = conversion.Method; if (group != null) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } method = CheckMethodGroupReceiverNullability(group, parameters, method, conversion.IsExtensionMethod); } if (reportRemainingWarnings && invokeSignature != null) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, targetType, invokeSignature, method, conversion.IsExtensionMethod); } } resultState = NullableFlowState.NotNull; break; static (MethodSymbol invokeSignature, ImmutableArray<ParameterSymbol>) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) => targetType switch { NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { Parameters: { } parameters } signature } => (signature, parameters), FunctionPointerTypeSymbol { Signature: { Parameters: { } parameters } signature } => (signature, parameters), _ => (null, ImmutableArray<ParameterSymbol>.Empty), }; case ConversionKind.AnonymousFunction: if (conversionOperand is BoundLambda lambda) { var delegateType = targetType.GetDelegateType(); VisitLambda(lambda, delegateType, stateForLambda); if (reportRemainingWarnings) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, delegateType, lambda.UnboundLambda); } TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); return TypeWithState.Create(targetType, NullableFlowState.NotNull); } break; case ConversionKind.FunctionType: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedString: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedStringHandler: // https://github.com/dotnet/roslyn/issues/54583 Handle resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = visitNestedTargetTypedConstructs(); TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); break; case ConversionKind.ExplicitUserDefined: case ConversionKind.ImplicitUserDefined: return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt); case ConversionKind.ExplicitDynamic: case ConversionKind.ImplicitDynamic: resultState = getConversionResultState(operandType); break; case ConversionKind.Boxing: resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); break; case ConversionKind.Unboxing: if (targetType.IsNonNullableValueType()) { if (!operandType.IsNotNull && reportRemainingWarnings) { ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, diagnosticLocationOpt); } LearnFromNonNullTest(conversionOperand, ref State); } else { resultState = getUnboxingConversionResultState(operandType); } break; case ConversionKind.ImplicitThrow: resultState = NullableFlowState.NotNull; break; case ConversionKind.NoConversion: resultState = getConversionResultState(operandType); break; case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: checkConversion = false; goto case ConversionKind.Identity; case ConversionKind.Identity: // If the operand is an explicit conversion, and this identity conversion // is converting to the same type including nullability, skip the conversion // to avoid reporting redundant warnings. Also check useLegacyWarnings // since that value was used when reporting warnings for the explicit cast. // Don't skip the node when it's a user-defined conversion, as identity conversions // on top of user-defined conversions means that we're coming in from VisitUserDefinedConversion // and that any warnings caught by this recursive call of VisitConversion won't be redundant. if (useLegacyWarnings && conversionOperand is BoundConversion operandConversion && !operandConversion.ConversionKind.IsUserDefinedConversion()) { var explicitType = operandConversion.ConversionGroupOpt?.ExplicitType; if (explicitType?.Equals(targetTypeWithNullability, TypeCompareKind.ConsiderEverything) == true) { TrackAnalyzedNullabilityThroughConversionGroup( calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, targetType), conversionOpt, conversionOperand); return operandType; } } if (operandType.Type?.IsTupleType == true || conversionOperand.Kind == BoundKind.TupleLiteral) { goto case ConversionKind.ImplicitTuple; } goto case ConversionKind.ImplicitReference; case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: // Inherit state from the operand. if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State; break; case ConversionKind.ImplicitNullable: if (trackMembers) { Debug.Assert(conversionOperand != null); if (AreNullableAndUnderlyingTypes(targetType, operandType.Type, out TypeWithAnnotations underlyingType)) { // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int containingSlot = GetOrCreatePlaceholderSlot(conversionOpt); Debug.Assert(containingSlot > 0); TrackNullableStateOfNullableValue(containingSlot, targetType, conversionOperand, underlyingType.ToTypeWithState(), valueSlot); } } } if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = operandType.State; break; case ConversionKind.ExplicitNullable: if (operandType.Type?.IsNullableType() == true && !targetType.IsNullableType()) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. if (reportTopLevelWarnings && operandType.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, diagnosticLocationOpt); } // Mark the value as not nullable, regardless of whether it was known to be nullable, // because the implied call to `.Value` will only succeed if not null. if (conversionOperand != null) { LearnFromNonNullTest(conversionOperand, ref State); } } goto case ConversionKind.ImplicitNullable; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: if (trackMembers) { Debug.Assert(conversionOperand != null); switch (conversion.Kind) { case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int slot = GetOrCreatePlaceholderSlot(conversionOpt); if (slot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, targetType, operandType.Type, slot, valueSlot, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings); } } break; } } if (checkConversion && !targetType.IsErrorType()) { // https://github.com/dotnet/roslyn/issues/29699: Report warnings for user-defined conversions on tuple elements. conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = NullableFlowState.NotNull; break; case ConversionKind.Deconstruction: // Can reach here, with an error type, when the // Deconstruct method is missing or inaccessible. break; case ConversionKind.ExplicitEnumeration: // Can reach here, with an error type. break; default: Debug.Assert(targetType.IsValueType || targetType.IsErrorType()); break; } TypeWithState resultType = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, targetType); if (operandType.Type?.IsErrorType() != true && !targetType.IsErrorType()) { // Need to report all warnings that apply since the warnings can be suppressed individually. if (reportTopLevelWarnings) { ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, resultType, useLegacyWarnings, assignmentKind, parameterOpt, diagnosticLocationOpt); } if (reportRemainingWarnings && !canConvertNestedNullability) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocationOpt, operandType.Type, parameterOpt, targetType, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocationOpt, GetTypeAsDiagnosticArgument(operandType.Type), targetType); } } } TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; #nullable enable static TypeWithState calculateResultType(TypeWithAnnotations targetTypeWithNullability, bool fromExplicitCast, NullableFlowState resultState, bool isSuppressed, TypeSymbol targetType) { if (isSuppressed) { resultState = NullableFlowState.NotNull; } else if (fromExplicitCast && targetTypeWithNullability.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) { // An explicit cast to a nullable reference type introduces nullability resultState = targetType?.IsTypeParameterDisallowingAnnotationInCSharp8() == true ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } var resultType = TypeWithState.Create(targetType, resultState); return resultType; } static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; switch (state) { case NullableFlowState.MaybeNull: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == true) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && dependsOnTypeParameter(typeParameter1, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } break; case NullableFlowState.MaybeDefault: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == false) { return NullableFlowState.MaybeNull; } break; } return state; } // Converting to a less-derived type (object, interface, type parameter). // If the operand is MaybeNull, the result should be // MaybeNull (if the target type allows) or MaybeDefault otherwise. static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && targetType.Type is TypeParameterSymbol typeParameter2) { bool dependsOn = dependsOnTypeParameter(typeParameter1, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation); Debug.Assert(dependsOn); // If this case fails, add a corresponding test. if (dependsOn) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } return state; } // Converting to a more-derived type (struct, class, type parameter). // If the operand is MaybeNull or MaybeDefault, the result should be // MaybeDefault. static NullableFlowState getUnboxingConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } static NullableFlowState getConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } // If type parameter 1 depends on type parameter 2 (that is, if type parameter 2 appears // in the constraint types of type parameter 1), returns the effective annotation on // type parameter 2 in the constraints of type parameter 1. static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) { if (typeParameter1.Equals(typeParameter2, TypeCompareKind.AllIgnoreOptions)) { annotation = typeParameter1Annotation; return true; } bool dependsOn = false; var combinedAnnotation = NullableAnnotation.Annotated; foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol constraintTypeParameter && dependsOnTypeParameter(constraintTypeParameter, typeParameter2, constraintType.NullableAnnotation, out var constraintAnnotation)) { dependsOn = true; combinedAnnotation = combinedAnnotation.Meet(constraintAnnotation); } } if (dependsOn) { annotation = combinedAnnotation.Join(typeParameter1Annotation); return true; } annotation = default; return false; } NullableFlowState visitNestedTargetTypedConstructs() { switch (conversionOperand) { case BoundConditionalOperator { WasTargetTyped: true } conditional: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(conditional)); var info = ConditionalInfoForConversion[conditional]; Debug.Assert(info.Length == 2); var consequence = conditional.Consequence; (BoundExpression consequenceOperand, Conversion consequenceConversion) = RemoveConversion(consequence, includeExplicitConversions: false); var consequenceRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(consequence, consequenceOperand, consequenceConversion, targetTypeWithNullability, info[0].ResultType, info[0].State, info[0].EndReachable); var alternative = conditional.Alternative; (BoundExpression alternativeOperand, Conversion alternativeConversion) = RemoveConversion(alternative, includeExplicitConversions: false); var alternativeRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(alternative, alternativeOperand, alternativeConversion, targetTypeWithNullability, info[1].ResultType, info[1].State, info[1].EndReachable); ConditionalInfoForConversion.Remove(conditional); return consequenceRValue.State.Join(alternativeRValue.State); } case BoundConvertedSwitchExpression { WasTargetTyped: true } @switch: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(@switch)); var info = ConditionalInfoForConversion[@switch]; Debug.Assert(info.Length == @switch.SwitchArms.Length); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(info.Length); for (int i = 0; i < info.Length; i++) { var (state, armResultType, isReachable) = info[i]; var arm = @switch.SwitchArms[i].Value; var (operand, conversion) = RemoveConversion(arm, includeExplicitConversions: false); resultTypes.Add(ConvertConditionalOperandOrSwitchExpressionArmResult(arm, operand, conversion, targetTypeWithNullability, armResultType, state, isReachable)); } var resultState = BestTypeInferrer.GetNullableState(resultTypes); resultTypes.Free(); ConditionalInfoForConversion.Remove(@switch); return resultState; } case BoundObjectCreationExpression { WasTargetTyped: true }: case BoundUnconvertedObjectCreationExpression: return NullableFlowState.NotNull; case BoundUnconvertedConditionalOperator: case BoundUnconvertedSwitchExpression: return operandType.State; default: throw ExceptionUtilities.UnexpectedValue(conversionOperand.Kind); } } } private TypeWithState VisitUserDefinedConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) { Debug.Assert(!IsConditionalState); Debug.Assert(conversionOperand != null); Debug.Assert(targetTypeWithNullability.HasType); Debug.Assert(diagnosticLocation != null); Debug.Assert(conversion.Kind == ConversionKind.ExplicitUserDefined || conversion.Kind == ConversionKind.ImplicitUserDefined); TypeSymbol targetType = targetTypeWithNullability.Type; // cf. Binder.CreateUserDefinedConversion if (!conversion.IsValid) { var resultType = TypeWithState.Create(targetType, NullableFlowState.NotNull); TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; } // operand -> conversion "from" type // May be distinct from method parameter type for Nullable<T>. operandType = VisitConversion( conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt: diagnosticLocation); // Update method based on operandType: see https://github.com/dotnet/roslyn/issues/29605. // (see NullableReferenceTypesTests.ImplicitConversions_07). var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount == 1); Debug.Assert(operandType.Type is object); var parameter = method.Parameters[0]; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); TypeWithState underlyingOperandType = default; bool isLiftedConversion = false; if (operandType.Type.IsNullableType() && !parameterType.IsNullableType()) { var underlyingOperandTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); underlyingOperandType = underlyingOperandTypeWithAnnotations.ToTypeWithState(); isLiftedConversion = parameterType.Equals(underlyingOperandTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); } // conversion "from" type -> method parameter type NullableFlowState operandState = operandType.State; Location operandLocation = conversionOperand.Syntax.GetLocation(); _ = ClassifyAndVisitConversion( conversionOperand, parameterType, isLiftedConversion ? underlyingOperandType : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterOpt: parameter, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // in the case of a lifted conversion, we assume that the call to the operator occurs only if the argument is not-null if (!isLiftedConversion && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax.Location)) { LearnFromNonNullTest(conversionOperand, ref State); } // method parameter type -> method return type var methodReturnType = method.ReturnTypeWithAnnotations; operandType = GetLiftedReturnTypeIfNecessary(isLiftedConversion, methodReturnType, operandState); if (!isLiftedConversion || operandState.IsNotNull()) { var returnNotNull = operandState.IsNotNull() && method.ReturnNotNullIfParameterNotNull.Contains(parameter.Name); if (returnNotNull) { operandType = operandType.WithNotNullState(); } else { operandType = ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)); } } // method return type -> conversion "to" type // May be distinct from method return type for Nullable<T>. operandType = ClassifyAndVisitConversion( conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // conversion "to" type -> final type // We should only pass fromExplicitCast here. Given the following example: // // class A { public static explicit operator C(A a) => throw null!; } // class C // { // void M() => var c = (C?)new A(); // } // // This final conversion from the method return type "C" to the cast type "C?" is // where we will need to ensure that this is counted as an explicit cast, so that // the resulting operandType is nullable if that was introduced via cast. operandType = ClassifyAndVisitConversion( conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); return operandType; } private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) { if (_snapshotBuilderOpt is null) { return; } var conversionOpt = conversionExpression as BoundConversion; var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode && conversionOpt.Syntax.SpanStart != convertedNode.Syntax.SpanStart) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); TakeIncrementalSnapshot(conversionOpt); conversionOpt = conversionOpt.Operand as BoundConversion; } } private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) { var visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); visitResult = withType(visitResult, conversionOpt.Type); SetAnalyzedNullability(conversionOpt, visitResult); conversionOpt = conversionOpt.Operand as BoundConversion; } static VisitResult withType(VisitResult visitResult, TypeSymbol newType) => new VisitResult(TypeWithState.Create(newType, visitResult.RValueType.State), TypeWithAnnotations.Create(newType, visitResult.LValueType.NullableAnnotation)); } /// <summary> /// Return the return type for a lifted operator, given the nullability state of its operands. /// </summary> private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) { bool typeNeedsLifting = returnType.Type.IsNonNullableValueType(); TypeSymbol type = typeNeedsLifting ? MakeNullableOf(returnType) : returnType.Type; NullableFlowState state = returnType.ToTypeWithState().State.Join(operandState); return TypeWithState.Create(type, state); } private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) { if (isLifted) { var type = typeWithState.Type; if (type?.IsNullableType() == true) { return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); } } return typeWithState; } private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) { return isLifted ? GetLiftedReturnType(returnType, operandState) : returnType.ToTypeWithState(); } private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) { return compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(underlying)); } private TypeWithState ClassifyAndVisitConversion( BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) { Debug.Assert(operandType.Type is object); Debug.Assert(diagnosticLocation != null); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyStandardConversion(null, operandType.Type, targetType.Type, ref discardedUseSiteInfo); if (reportWarnings && !conversion.Exists) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); } } return VisitConversion( conversionOpt: null, conversionOperand: node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings: useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: !fromExplicitCast && reportWarnings, diagnosticLocationOpt: diagnosticLocation); } public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { Debug.Assert(node.Type.IsDelegateType()); if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { VisitMethodGroup(group); var method = node.MethodOpt; if (method is object) { method = CheckMethodGroupReceiverNullability(group, delegateType.DelegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, method, node.IsExtensionMethod); } } SetAnalyzedNullability(group, default); } break; case BoundLambda lambda: { VisitLambda(lambda, delegateType); SetNotNullResult(lambda); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda.UnboundLambda); } } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate } argType: { var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); if (!arg.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, argType.DelegateInvokeMethod(), invokedAsExtensionMethod: false); } // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); } break; default: VisitRvalue(node.Argument); break; } SetNotNullResult(node); return null; } public override BoundNode? VisitMethodGroup(BoundMethodGroup node) { Debug.Assert(!IsConditionalState); var receiverOpt = node.ReceiverOpt; if (receiverOpt != null) { VisitRvalue(receiverOpt); // Receiver nullability is checked when applying the method group conversion, // when we have a specific method, to avoid reporting null receiver warnings // for extension method delegates. Here, store the receiver state for that check. SetMethodGroupReceiverNullability(receiverOpt, ResultType); } SetNotNullResult(node); return null; } private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) { if (receiverOpt != null && _methodGroupReceiverMapOpt != null && _methodGroupReceiverMapOpt.TryGetValue(receiverOpt, out type)) { return true; } else { type = default; return false; } } private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) { _methodGroupReceiverMapOpt ??= PooledDictionary<BoundExpression, TypeWithState>.GetInstance(); _methodGroupReceiverMapOpt[receiver] = type; } private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray<ParameterSymbol> parameters, MethodSymbol method, bool invokedAsExtensionMethod) { var receiverOpt = group.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { var syntax = group.Syntax; if (!invokedAsExtensionMethod) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) { var arguments = ArrayBuilder<BoundExpression>.GetInstance(); if (invokedAsExtensionMethod) { arguments.Add(CreatePlaceholderIfNecessary(receiverOpt, receiverType.ToTypeWithAnnotations(compilation))); } // Create placeholders for the arguments. (See Conversions.GetDelegateArguments() // which is used for that purpose in initial binding.) foreach (var parameter in parameters) { var parameterType = parameter.TypeWithAnnotations; arguments.Add(new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, parameter), parameterType.NullableAnnotation, parameterType.Type)); } Debug.Assert(_binder is object); method = InferMethodTypeArguments(method, arguments.ToImmutableAndFree(), argumentRefKindsOpt: default, argsToParamsOpt: default, expanded: false); } if (invokedAsExtensionMethod) { CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], receiverType); } else { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } if (ConstraintsHelper.RequiresChecking(method)) { CheckMethodConstraints(syntax, method); } } return method; } public override BoundNode? VisitLambda(BoundLambda node) { // Note: actual lambda analysis happens after this call (primarily in VisitConversion). // Here we just indicate that a lambda expression produces a non-null value. SetNotNullResult(node); return null; } private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional<LocalState> initialState = default) { Debug.Assert(delegateTypeOpt?.IsDelegateType() != false); var delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt is object) { SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt!); } AnalyzeLocalFunctionOrLambda( node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); } private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) { if (delegateInvokeMethod is null) { useDelegateInvokeParameterTypes = false; useDelegateInvokeReturnType = false; } else { var unboundLambda = lambda.UnboundLambda; useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out _, out _); } } public override BoundNode? VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. // Analyze the body to report any additional warnings. var lambda = node.BindForErrorRecovery(); VisitLambda(lambda, delegateTypeOpt: null); SetNotNullResult(node); return null; } public override BoundNode? VisitThisReference(BoundThisReference node) { VisitThisOrBaseReference(node); return null; } private void VisitThisOrBaseReference(BoundExpression node) { var rvalueResult = TypeWithState.Create(node.Type, NullableFlowState.NotNull); var lvalueResult = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); SetResult(node, rvalueResult, lvalueResult); } public override BoundNode? VisitParameter(BoundParameter node) { var parameter = node.ParameterSymbol; int slot = GetOrCreateSlot(parameter); var parameterType = GetDeclaredParameterResult(parameter); var typeWithState = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations); SetResult(node, GetAdjustedResult(typeWithState, slot), parameterType); return null; } public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { Debug.Assert(!IsConditionalState); var left = node.Left; switch (left) { // when binding initializers, we treat assignments to auto-properties or field-like events as direct assignments to the underlying field. // in order to track member state based on these initializers, we need to see the assignment in terms of the associated member case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: PropertySymbol autoProperty } } fieldAccess: left = new BoundPropertyAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, autoProperty, LookupResultKind.Viable, autoProperty.Type, fieldAccess.HasErrors); break; case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: EventSymbol @event } } fieldAccess: left = new BoundEventAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, @event, isUsableAsField: true, LookupResultKind.Viable, @event.Type, fieldAccess.HasErrors); break; } var right = node.Right; VisitLValue(left); // we may enter a conditional state for error scenarios on the LHS. Unsplit(); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to an Add method. (Note that assignment // of non-field-like events uses BoundEventAssignmentOperator // rather than BoundAssignmentOperator.) VisitRvalue(right); SetNotNullResult(node); } else { TypeWithState rightState; if (!node.IsRef) { var discarded = left is BoundDiscardExpression; rightState = VisitOptionalImplicitConversion(right, targetTypeOpt: discarded ? default : leftLValueType, UseLegacyWarnings(left, leftLValueType), trackMembers: true, AssignmentKind.Assignment); } else { rightState = VisitRefExpression(right, leftLValueType); } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(rightState, leftAnnotations, right.Syntax.Location); AdjustSetValue(left, ref rightState); TrackNullableStateForAssignment(right, leftLValueType, MakeSlot(left), rightState, MakeSlot(right)); if (left is BoundDiscardExpression) { var lvalueType = rightState.ToTypeWithAnnotations(compilation); SetResult(left, rightState, lvalueType, isLvalue: true); SetResult(node, rightState, lvalueType); } else { SetResult(node, TypeWithState.Create(leftLValueType.Type, rightState.State), leftLValueType); } } return null; } private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) { var type = property.TypeWithAnnotations; var annotations = IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : property.GetFlowAnalysisAnnotations(); var lValueType = ApplyLValueAnnotations(type, annotations); if (lValueType.NullableAnnotation.IsOblivious() || !lValueType.CanBeAssignedNull) { return false; } var rValueType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), annotations); return rValueType.IsNotNull; } /// <summary> /// When the allowed output of a property/indexer is not-null but the allowed input is maybe-null, we store a not-null value instead. /// This way, assignment of a legal input value results in a legal output value. /// This adjustment doesn't apply to oblivious properties/indexers. /// </summary> private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) { var property = left switch { BoundPropertyAccess propAccess => propAccess.PropertySymbol, BoundIndexerAccess indexerAccess => indexerAccess.Indexer, _ => null }; if (property is not null && IsPropertyOutputMoreStrictThanInput(property)) { rightState = rightState.WithNotNullState(); } } private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = expr switch { BoundPropertyAccess property => property.PropertySymbol.GetFlowAnalysisAnnotations(), BoundIndexerAccess indexer => indexer.Indexer.GetFlowAnalysisAnnotations(), BoundFieldAccess field => getFieldAnnotations(field.FieldSymbol), BoundObjectInitializerMember { MemberSymbol: PropertySymbol prop } => prop.GetFlowAnalysisAnnotations(), BoundObjectInitializerMember { MemberSymbol: FieldSymbol field } => getFieldAnnotations(field), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); static FlowAnalysisAnnotations getFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } } private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) { var annotations = FlowAnalysisAnnotations.None; if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen count as MaybeNull annotations |= FlowAnalysisAnnotations.AllowNull; } if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNullWhenTrue and NotNullWhenFalse don't count on their own. Only NotNull (ie. both flags) matters. annotations |= FlowAnalysisAnnotations.DisallowNull; } return annotations; } private static bool UseLegacyWarnings(BoundExpression expr, TypeWithAnnotations exprType) { switch (expr.Kind) { case BoundKind.Local: return expr.GetRefKind() == RefKind.None; case BoundKind.Parameter: RefKind kind = ((BoundParameter)expr).ParameterSymbol.RefKind; return kind == RefKind.None; default: return false; } } public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return VisitDeconstructionAssignmentOperator(node, rightResultOpt: null); } private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) { var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; _disableNullabilityAnalysis = true; var left = node.Left; var right = node.Right; var variables = GetDeconstructionAssignmentVariables(left); if (node.HasErrors) { // In the case of errors, simply visit the right as an r-value to update // any nullability state even though deconstruction is skipped. VisitRvalue(right.Operand); } else { VisitDeconstructionArguments(variables, right.Conversion, right.Operand, rightResultOpt); } variables.FreeAll(v => v.NestedVariables); // https://github.com/dotnet/roslyn/issues/33011: Result type should be inferred and the constraints should // be re-verified. Even though the standard tuple type has no constraints we support that scenario. Constraints_78 // has a test for this case that should start failing when this is fixed. SetNotNullResult(node); _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; return null; } private void VisitDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) { Debug.Assert(conversion.Kind == ConversionKind.Deconstruction); if (!conversion.DeconstructionInfo.IsDefault) { VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); } else { VisitTupleDeconstructionArguments(variables, conversion.UnderlyingConversions, right); } } private void VisitDeconstructMethodArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) { VisitRvalue(right); // If we were passed an explicit right result, use that rather than the visited result if (rightResultOpt.HasValue) { SetResultType(right, rightResultOpt.Value); } var rightResult = ResultType; var invocation = conversion.DeconstructionInfo.Invocation as BoundCall; var deconstructMethod = invocation?.Method; if (deconstructMethod is object) { Debug.Assert(invocation is object); Debug.Assert(rightResult.Type is object); int n = variables.Count; if (!invocation.InvokedAsExtensionMethod) { _ = CheckPossibleNullReceiver(right); // update the deconstruct method with any inferred type parameters of the containing type if (deconstructMethod.OriginalDefinition != deconstructMethod) { deconstructMethod = deconstructMethod.OriginalDefinition.AsMember((NamedTypeSymbol)rightResult.Type); } } else { if (deconstructMethod.IsGenericMethod) { // re-infer the deconstruct parameters based on the 'this' parameter ArrayBuilder<BoundExpression> placeholderArgs = ArrayBuilder<BoundExpression>.GetInstance(n + 1); placeholderArgs.Add(CreatePlaceholderIfNecessary(right, rightResult.ToTypeWithAnnotations(compilation))); for (int i = 0; i < n; i++) { placeholderArgs.Add(new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); } deconstructMethod = InferMethodTypeArguments(deconstructMethod, placeholderArgs.ToImmutableAndFree(), invocation.ArgumentRefKindsOpt, invocation.ArgsToParamsOpt, invocation.Expanded); // check the constraints remain valid with the re-inferred parameter types if (ConstraintsHelper.RequiresChecking(deconstructMethod)) { CheckMethodConstraints(invocation.Syntax, deconstructMethod); } } } var parameters = deconstructMethod.Parameters; int offset = invocation.InvokedAsExtensionMethod ? 1 : 0; Debug.Assert(parameters.Length - offset == n); if (invocation.InvokedAsExtensionMethod) { // Check nullability for `this` parameter var argConversion = RemoveConversion(invocation.Arguments[0], includeExplicitConversions: false).conversion; CheckExtensionMethodThisNullability(right, argConversion, deconstructMethod.Parameters[0], rightResult); } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var underlyingConversion = conversion.UnderlyingConversions[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { var nestedRight = CreatePlaceholderIfNecessary(invocation.Arguments[i + offset], parameter.TypeWithAnnotations); VisitDeconstructionArguments(nestedVariables, underlyingConversion, right: nestedRight); } else { VisitArgumentConversionAndInboundAssignmentsAndPreConditions(conversionOpt: null, variable.Expression, underlyingConversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), extensionMethodThisArgument: false); } } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var nestedVariables = variable.NestedVariables; if (nestedVariables == null) { VisitArgumentOutboundAssignmentsAndPostConditions( variable.Expression, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetRValueAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), notNullParametersOpt: null, compareExchangeInfoOpt: default); } } } } private void VisitTupleDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<Conversion> conversions, BoundExpression right) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var underlyingConversion = conversions[i]; var rightPart = rightParts[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { VisitDeconstructionArguments(nestedVariables, underlyingConversion, rightPart); } else { var lvalueType = variable.Type; var leftAnnotations = GetLValueAnnotations(variable.Expression); lvalueType = ApplyLValueAnnotations(lvalueType, leftAnnotations); TypeWithState operandType; TypeWithState valueType; int valueSlot; if (underlyingConversion.IsIdentity) { if (variable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } local) { // when the LHS is a var declaration, we can just visit the right part to infer the type valueType = operandType = VisitRvalueWithState(rightPart); _variables.SetType(local.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); } else { operandType = default; valueType = VisitOptionalImplicitConversion(rightPart, lvalueType, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } valueSlot = MakeSlot(rightPart); } else { operandType = VisitRvalueWithState(rightPart); valueType = VisitConversion( conversionOpt: null, rightPart, underlyingConversion, lvalueType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment, reportTopLevelWarnings: true, reportRemainingWarnings: true, trackMembers: false); valueSlot = -1; } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(valueType, leftAnnotations, right.Syntax.Location); int targetSlot = MakeSlot(variable.Expression); AdjustSetValue(variable.Expression, ref valueType); TrackNullableStateForAssignment(rightPart, lvalueType, targetSlot, valueType, valueSlot); // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (targetSlot > 0 && underlyingConversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(lvalueType.Type, operandType.Type, out TypeWithAnnotations underlyingType)) { valueSlot = MakeSlot(rightPart); if (valueSlot > 0) { var valueBeforeNullableWrapping = TypeWithState.Create(underlyingType.Type, NullableFlowState.NotNull); TrackNullableStateOfNullableValue(targetSlot, lvalueType.Type, rightPart, valueBeforeNullableWrapping, valueSlot); } } } } } private readonly struct DeconstructionVariable { internal readonly BoundExpression Expression; internal readonly TypeWithAnnotations Type; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) { Expression = expression; Type = type; NestedVariables = null; } internal DeconstructionVariable(BoundExpression expression, ArrayBuilder<DeconstructionVariable> nestedVariables) { Expression = expression; Type = default; NestedVariables = nestedVariables; } } private ArrayBuilder<DeconstructionVariable> GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) { var arguments = tuple.Arguments; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(arguments.Length); foreach (var argument in arguments) { builder.Add(getDeconstructionAssignmentVariable(argument)); } return builder; DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); default: VisitLValue(expr); return new DeconstructionVariable(expr, LvalueResultType); } } } /// <summary> /// Return the sub-expressions for the righthand side of a deconstruction /// assignment. cf. LocalRewriter.GetRightParts. /// </summary> private ImmutableArray<BoundExpression> GetDeconstructionRightParts(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return ((BoundTupleExpression)expr).Arguments; case BoundKind.Conversion: { var conv = (BoundConversion)expr; switch (conv.ConversionKind) { case ConversionKind.Identity: case ConversionKind.ImplicitTupleLiteral: return GetDeconstructionRightParts(conv.Operand); } } break; } if (expr.Type is NamedTypeSymbol { IsTupleType: true } tupleType) { // https://github.com/dotnet/roslyn/issues/33011: Should include conversion.UnderlyingConversions[i]. // For instance, Boxing conversions (see Deconstruction_ImplicitBoxingConversion_02) and // ImplicitNullable conversions (see Deconstruction_ImplicitNullableConversion_02). var fields = tupleType.TupleElements; return fields.SelectAsArray((f, e) => (BoundExpression)new BoundFieldAccess(e.Syntax, e, f, constantValueOpt: null), expr); } throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) { Debug.Assert(!IsConditionalState); var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 // https://github.com/dotnet/roslyn/issues/29961 Update conversion method based on operand type. if (node.OperandConversion.IsUserDefined && node.OperandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = node.OperandConversion.Method.ReturnTypeWithAnnotations; } else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } else { // Either a built-in increment, or an error case. targetTypeOfOperandConversion = default; } TypeWithState resultOfOperandConversionType; if (targetTypeOfOperandConversion.HasType) { // https://github.com/dotnet/roslyn/issues/29961 Should something special be done for targetTypeOfOperandConversion for lifted case? resultOfOperandConversionType = VisitConversion( conversionOpt: null, node.Operand, node.OperandConversion, targetTypeOfOperandConversion, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true); } else { resultOfOperandConversionType = operandType; } TypeWithState resultOfIncrementType; if (incrementOperator is null) { resultOfIncrementType = resultOfOperandConversionType; } else { resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); resultOfIncrementType = VisitConversion( conversionOpt: null, node, node.ResultConversion, operandTypeWithAnnotations, resultOfIncrementType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // https://github.com/dotnet/roslyn/issues/29961 Check node.Type.IsErrorType() instead? if (!node.HasErrors) { var op = node.OperatorKind.Operator(); TypeWithState resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType; SetResultType(node, resultType); setResult = true; TrackNullableStateForAssignment(node, targetType: operandLvalue, targetSlot: MakeSlot(node.Operand), valueType: resultOfIncrementType); } } if (!setResult) { SetNotNullResult(node); } return null; } public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { var left = node.Left; var right = node.Right; Visit(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = declaredType; TypeWithState leftResultType = ResultType; Debug.Assert(!IsConditionalState); TypeWithState leftOnRightType = GetAdjustedResult(leftResultType, MakeSlot(node.Left)); // https://github.com/dotnet/roslyn/issues/29962 Update operator based on inferred argument types. if ((object)node.Operator.LeftType != null) { // https://github.com/dotnet/roslyn/issues/29962 Ignoring top-level nullability of operator left parameter. leftOnRightType = VisitConversion( conversionOpt: null, node.Left, node.LeftConversion, TypeWithAnnotations.Create(node.Operator.LeftType), leftOnRightType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: true); } else { leftOnRightType = default; } TypeWithState resultType; TypeWithState rightType = VisitRvalueWithState(right); if ((object)node.Operator.ReturnType != null) { if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(node.Left); leftLValueType = ApplyLValueAnnotations(leftLValueType, leftAnnotations); resultType = VisitConversion( conversionOpt: null, node, node.FinalConversion, leftLValueType, resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, leftAnnotations, node.Syntax.Location); } else { resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); } AdjustSetValue(left, ref resultType); TrackNullableStateForAssignment(node, leftLValueType, MakeSlot(node.Left), resultType); SetResultType(node, resultType); return null; } public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { var initializer = node.Expression; if (initializer.Kind == BoundKind.AddressOfOperator) { initializer = ((BoundAddressOfOperator)initializer).Operand; } VisitRvalue(initializer); if (node.Expression.Kind == BoundKind.AddressOfOperator) { SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); } SetNotNullResult(node); return null; } public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) { Visit(node.Operand); SetNotNullResult(node); return null; } private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) { var paramType = parameter.TypeWithAnnotations; ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) { ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); } } private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); } /// <summary> /// Report warning passing argument where nested nullability does not match /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`). /// </summary> private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) { ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); } private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) { ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, parameterOpt?.Type.IsNonNullableValueType() == true && parameterType.IsNullableType() ? parameterOpt.Type : parameterType, // Compensate for operator lifting GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); } private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) { return _variables.TryGetType(local, out TypeWithAnnotations type) ? type : local.TypeWithAnnotations; } private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) { return _variables.TryGetType(parameter, out TypeWithAnnotations type) ? type : parameter.TypeWithAnnotations; } public override BoundNode? VisitBaseReference(BoundBaseReference node) { VisitThisOrBaseReference(node); return null; } public override BoundNode? VisitFieldAccess(BoundFieldAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); return null; } public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; var updatedMember = VisitMemberAccess(node, node.ReceiverOpt, property); if (!IsAnalyzingAttribute) { if (_expressionIsRead) { ApplyMemberPostConditions(node.ReceiverOpt, property.GetMethod); } else { ApplyMemberPostConditions(node.ReceiverOpt, property.SetMethod); } } SetUpdatedSymbol(node, property, updatedMember); return null; } public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) { var receiverOpt = node.ReceiverOpt; var receiverType = VisitRvalueWithState(receiverOpt).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); var indexer = node.Indexer; if (receiverType is object) { // Update indexer based on inferred receiver type. indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); SetUpdatedSymbol(node, node.Indexer, indexer); return null; } public override BoundNode? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { BoundExpression receiver = node.Receiver; var receiverType = VisitRvalueWithState(receiver).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitRvalue(node.Argument); var patternSymbol = node.PatternSymbol; if (receiverType is object) { patternSymbol = AsMemberOfType(receiverType, patternSymbol); } SetLvalueResultType(node, patternSymbol.GetTypeOrReturnType()); SetUpdatedSymbol(node, node.PatternSymbol, patternSymbol); return null; } public override BoundNode? VisitEventAccess(BoundEventAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); return null; } private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) { Debug.Assert(!IsConditionalState); var receiverType = (receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default; SpecialMember? nullableOfTMember = null; if (member.RequiresInstanceReceiver()) { member = AsMemberOfType(receiverType.Type, member); nullableOfTMember = GetNullableOfTMember(member); // https://github.com/dotnet/roslyn/issues/30598: For l-values, mark receiver as not null // after RHS has been visited, and only if the receiver has not changed. bool skipReceiverNullCheck = nullableOfTMember != SpecialMember.System_Nullable_T_get_Value; _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType: !skipReceiverNullCheck); } var type = member.GetTypeOrReturnType(); var memberAnnotations = GetRValueAnnotations(member); var resultType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), memberAnnotations); // We are supposed to track information for the node. Use whatever we managed to // accumulate so far. if (PossiblyNullableType(resultType.Type)) { int slot = MakeMemberSlot(receiverOpt, member); if (this.State.HasValue(slot)) { var state = this.State[slot]; resultType = TypeWithState.Create(resultType.Type, state); } } Debug.Assert(!IsConditionalState); if (nullableOfTMember == SpecialMember.System_Nullable_T_get_HasValue && !(receiverOpt is null)) { int containingSlot = MakeSlot(receiverOpt); if (containingSlot > 0) { Split(); this.StateWhenTrue[containingSlot] = NullableFlowState.NotNull; } } SetResult(node, resultType, type); return member; } private SpecialMember? GetNullableOfTMember(Symbol member) { if (member.Kind == SymbolKind.Property) { var getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; if ((object)getMethod != null && getMethod.ContainingType.SpecialType == SpecialType.System_Nullable_T) { if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { return SpecialMember.System_Nullable_T_get_Value; } if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue)) { return SpecialMember.System_Nullable_T_get_HasValue; } } } return null; } private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) { Debug.Assert(containingType.IsNullableType()); Debug.Assert(TypeSymbol.Equals(NominalSlotType(containingSlot), containingType, TypeCompareKind.ConsiderEverything2)); var getValue = (MethodSymbol)compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value); valueProperty = getValue?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; return (valueProperty is null) ? -1 : GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty: forceSlotEvenIfEmpty); } protected override void VisitForEachExpression(BoundForEachStatement node) { if (node.Expression.Kind != BoundKind.Conversion) { // If we're in this scenario, there was a binding error, and we should suppress any further warnings. Debug.Assert(node.HasErrors); VisitRvalue(node.Expression); return; } var (expr, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(node.Expression, expr); // There are 7 ways that a foreach can be created: // 1. The collection type is an array type. For this, initial binding will generate an implicit reference conversion to // IEnumerable, and we do not need to do any reinferring of enumerators here. // 2. The collection type is dynamic. For this we do the same as 1. // 3. The collection type implements the GetEnumerator pattern. For this, there is an identity conversion. Because // this identity conversion uses nested types from initial binding, we cannot trust them and must instead use // the type of the expression returned from VisitResult to reinfer the enumerator information. // 4. The collection type implements IEnumerable<T>. Only a few cases can hit this without being caught by number 3, // such as a type with a private implementation of IEnumerable<T>, or a type parameter constrained to that type. // In these cases, there will be an implicit conversion to IEnumerable<T>, but this will use types from // initial binding. For this scenario, we need to look through the list of implemented interfaces on the type and // find the version of IEnumerable<T> that it has after nullable analysis, as type substitution could have changed // nested nullability of type parameters. See ForEach_22 for a concrete example of this. // 5. The collection type implements IEnumerable (non-generic). Because this version isn't generic, we don't need to // do any reinference, and the existing conversion can stand as is. // 6. The target framework's System.String doesn't implement IEnumerable. This is a compat case: System.String normally // does implement IEnumerable, but there are certain target frameworks where this isn't the case. The compiler will // still emit code for foreach in these scenarios. // 7. The collection type implements the GetEnumerator pattern via an extension GetEnumerator. For this, there will be // conversion to the parameter of the extension method. // 8. Some binding error occurred, and some other error has already been reported. Usually this doesn't have any kind // of conversion on top, but if there was an explicit conversion in code then we could get past the initial check // for a BoundConversion node. var resultTypeWithState = VisitRvalueWithState(expr); var resultType = resultTypeWithState.Type; Debug.Assert(resultType is object); SetAnalyzedNullability(expr, _visitResult); TypeWithAnnotations targetTypeWithAnnotations; MethodSymbol? reinferredGetEnumeratorMethod = null; if (node.EnumeratorInfoOpt?.GetEnumeratorInfo is { Method: { IsExtensionMethod: true, Parameters: var parameters } } enumeratorMethodInfo) { // this is case 7 // We do not need to do this same analysis for non-extension methods because they do not have generic parameters that // can be inferred from usage like extension methods can. We don't warn about default arguments at the call site, so // there's nothing that can be learned from the non-extension case. var (method, results, _) = VisitArguments( node, enumeratorMethodInfo.Arguments, refKindsOpt: default, parameters, argsToParamsOpt: enumeratorMethodInfo.ArgsToParamsOpt, defaultArguments: enumeratorMethodInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, enumeratorMethodInfo.Method); targetTypeWithAnnotations = results[0].LValueType; reinferredGetEnumeratorMethod = method; } else if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && resultType.SpecialType == SpecialType.System_String)) { // This is case 3 or 6. targetTypeWithAnnotations = resultTypeWithState.ToTypeWithAnnotations(compilation); } else if (conversion.IsImplicit) { bool isAsync = node.AwaitOpt != null; if (node.Expression.Type!.SpecialType == SpecialType.System_Collections_IEnumerable) { // If this is a conversion to IEnumerable (non-generic), nothing to do. This is cases 1, 2, and 5. targetTypeWithAnnotations = TypeWithAnnotations.Create(node.Expression.Type); } else if (ForEachLoopBinder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) { // This is case 4. We need to look for the IEnumerable<T> that this reinferred expression implements, // so that we pick up any nested type substitutions that could have occurred. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; targetTypeWithAnnotations = TypeWithAnnotations.Create(ForEachLoopBinder.GetIEnumerableOfT(resultType, isAsync, compilation, ref discardedUseSiteInfo, out bool foundMultiple)); Debug.Assert(!foundMultiple); Debug.Assert(targetTypeWithAnnotations.HasType); } else { // This is case 8. There was not a successful binding, as a successful binding will _always_ generate one of the // above conversions. Just return, as we want to suppress further errors. return; } } else { // This is also case 8. return; } var convertedResult = VisitConversion( GetConversionIfApplicable(node.Expression, expr), expr, conversion, targetTypeWithAnnotations, resultTypeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); bool reportedDiagnostic = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method is { IsExtensionMethod: true } ? false : CheckPossibleNullReceiver(expr); SetAnalyzedNullability(node.Expression, new VisitResult(convertedResult, convertedResult.ToTypeWithAnnotations(compilation))); TypeWithState currentPropertyGetterTypeWithState; if (node.EnumeratorInfoOpt is null) { currentPropertyGetterTypeWithState = default; } else if (resultType is ArrayTypeSymbol arrayType) { // Even though arrays use the IEnumerator pattern, we use the array element type as the foreach target type, so // directly get our source type from there instead of doing method reinference. currentPropertyGetterTypeWithState = arrayType.ElementTypeWithAnnotations.ToTypeWithState(); } else if (resultType.SpecialType == SpecialType.System_String) { // There are frameworks where System.String does not implement IEnumerable, but we still lower it to a for loop // using the indexer over the individual characters anyway. So the type must be not annotated char. currentPropertyGetterTypeWithState = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); } else { // Reinfer the return type of the node.Expression.GetEnumerator().Current property, so that if // the collection changed nested generic types we pick up those changes. reinferredGetEnumeratorMethod ??= (MethodSymbol)AsMemberOfType(convertedResult.Type, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); var enumeratorReturnType = GetReturnTypeWithState(reinferredGetEnumeratorMethod); if (enumeratorReturnType.State != NullableFlowState.NotNull) { if (!reportedDiagnostic && !(node.Expression is BoundConversion { Operand: { IsSuppressed: true } })) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, expr.Syntax.GetLocation()); } } var currentPropertyGetter = (MethodSymbol)AsMemberOfType(enumeratorReturnType.Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); // Analyze `await MoveNextAsync()` if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) { var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); Visit(awaitMoveNextInfo); _awaitablePlaceholdersOpt.Remove(moveNextPlaceholder); } // Analyze `await DisposeAsync()` if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) { var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; bool addedPlaceholder = false; if (node.EnumeratorInfoOpt.PatternDisposeInfo is { Method: var originalDisposeMethod }) // no statically known Dispose method if doing a runtime check { Debug.Assert(disposalPlaceholder is not null); var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, originalDisposeMethod); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { _awaitablePlaceholdersOpt!.Remove(disposalPlaceholder!); } } } SetResultType(expression: null, currentPropertyGetterTypeWithState); } public override void VisitForEachIterationVariables(BoundForEachStatement node) { // ResultType should have been set by VisitForEachExpression, called just before this. var sourceState = node.EnumeratorInfoOpt == null ? default : ResultType; TypeWithAnnotations sourceType = sourceState.ToTypeWithAnnotations(compilation); #pragma warning disable IDE0055 // Fix formatting var variableLocation = node.Syntax switch { ForEachStatementSyntax statement => statement.Identifier.GetLocation(), ForEachVariableStatementSyntax variableStatement => variableStatement.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Syntax) }; #pragma warning restore IDE0055 // Fix formatting if (node.DeconstructionOpt is object) { var assignment = node.DeconstructionOpt.DeconstructionAssignment; // Visit the assignment as a deconstruction with an explicit type VisitDeconstructionAssignmentOperator(assignment, sourceState.HasNullType ? (TypeWithState?)null : sourceState); // https://github.com/dotnet/roslyn/issues/35010: if the iteration variable is a tuple deconstruction, we need to put something in the tree Visit(node.IterationVariableType); } else { Visit(node.IterationVariableType); foreach (var iterationVariable in node.IterationVariables) { var state = NullableFlowState.NotNull; if (!sourceState.HasNullType) { TypeWithAnnotations destinationType = iterationVariable.TypeWithAnnotations; TypeWithState result = sourceState; TypeWithState resultForType = sourceState; if (iterationVariable.IsRef) { // foreach (ref DestinationType variable in collection) if (IsNullabilityMismatch(sourceType, destinationType)) { var foreachSyntax = (ForEachStatementSyntax)node.Syntax; ReportNullabilityMismatchInAssignment(foreachSyntax.Type, sourceType, destinationType); } } else if (iterationVariable is SourceLocalSymbol { IsVar: true }) { // foreach (var variable in collection) destinationType = sourceState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(iterationVariable, destinationType); resultForType = destinationType.ToTypeWithState(); } else { // foreach (DestinationType variable in collection) // and asynchronous variants var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion conversion = node.ElementConversion.Kind == ConversionKind.UnsetConversionKind ? _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo) : node.ElementConversion; result = VisitConversion( conversionOpt: null, conversionOperand: node.IterationVariableType, conversion, destinationType, sourceState, checkConversion: true, fromExplicitCast: !conversion.IsImplicit, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, reportTopLevelWarnings: true, reportRemainingWarnings: true, diagnosticLocationOpt: variableLocation); } // In non-error cases we'll only run this loop a single time. In error cases we'll set the nullability of the VariableType multiple times, but at least end up with something SetAnalyzedNullability(node.IterationVariableType, new VisitResult(resultForType, destinationType), isLvalue: true); state = result.State; } int slot = GetOrCreateSlot(iterationVariable); if (slot > 0) { this.State[slot] = state; } } } } public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { var result = base.VisitFromEndIndexExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Should be handled by VisitObjectCreationExpression. throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { SetNotNullResult(node); return null; } public override BoundNode? VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { // https://github.com/dotnet/roslyn/issues/35042, we need to implement similar workarounds for object, collection, and dynamic initializers. if (child is BoundLambda lambda) { TakeIncrementalSnapshot(lambda); VisitLambda(lambda, delegateTypeOpt: null); VisitRvalueEpilogue(lambda); } else { VisitRvalue(child as BoundExpression); } } var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return null; } public override BoundNode? VisitTypeExpression(BoundTypeExpression node) { var result = base.VisitTypeExpression(node); if (node.BoundContainingTypeOpt != null) { VisitTypeExpression(node.BoundContainingTypeOpt); } SetNotNullResult(node); return result; } public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // These should not appear after initial binding except in error cases. var result = base.VisitTypeOrValueExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) { Debug.Assert(!IsConditionalState); TypeWithState resultType; switch (node.OperatorKind) { case UnaryOperatorKind.BoolLogicalNegation: Visit(node.Operand); if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicTrue: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicLogicalNegation: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); // If the state is split, the result is `bool` at runtime and we invert it here. if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; default: if (node.OperatorKind.IsUserDefined() && node.MethodOpt is MethodSymbol method && method.ParameterCount == 1) { var (operand, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); VisitRvalue(operand); var operandResult = ResultType; bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( node.Operand as BoundConversion, operand, conversion, parameter.TypeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter); resultType = GetLiftedReturnTypeIfNecessary(isLifted, method.ReturnTypeWithAnnotations, operandResult.State); SetUpdatedSymbol(node, node.MethodOpt, method); } else { VisitRvalue(node.Operand); resultType = adjustForLifting(ResultType); } break; } SetResultType(node, resultType); return null; TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) { var result = base.VisitPointerElementAccess(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); SetNotNullResult(node); return null; } public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) { var result = base.VisitMakeRefOperator(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) { var result = base.VisitRefValueOperator(node); var type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetLvalueResultType(node, type); return result; } private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) { if (node.OperatorKind.IsLifted()) { // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator // Should this use the updated flow type and state? How should it compute nullability? return TypeWithState.Create(node.Type, NullableFlowState.NotNull); } // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) { return GetReturnTypeWithState(node.LogicalOperator); } else { return default; } } protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { Debug.Assert(!IsConditionalState); TypeWithState leftType = ResultType; // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. MethodSymbol? logicalOperator = null; MethodSymbol? trueFalseOperator = null; BoundExpression? left = null; switch (node.Kind) { case BoundKind.BinaryOperator: Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); break; case BoundKind.UserDefinedConditionalLogicalOperator: var binary = (BoundUserDefinedConditionalLogicalOperator)node; if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) { logicalOperator = binary.LogicalOperator; left = binary.Left; trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) { trueFalseOperator = null; } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } Debug.Assert(trueFalseOperator is null || logicalOperator is object); Debug.Assert(logicalOperator is null || left is object); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if (trueFalseOperator is object) { ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); } if (logicalOperator is object) { ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); } Visit(right); TypeWithState rightType = ResultType; SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); if (logicalOperator is object) { ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); } AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse); } private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) { return node switch { BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), _ => throw ExceptionUtilities.UnexpectedValue(node) }; } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { var result = base.VisitAwaitExpression(node); var awaitableInfo = node.AwaitableInfo; var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(placeholder); if (node.Type.IsValueType || node.HasErrors || awaitableInfo.GetResult is null) { SetNotNullResult(node); } else { // It is possible for the awaiter type returned from GetAwaiter to not be a named type. e.g. it could be a type parameter. // Proper handling of this is additional work which only benefits a very uncommon scenario, // so we will just use the originally bound GetResult method in this case. var getResult = awaitableInfo.GetResult; var reinferredGetResult = _visitResult.RValueType.Type is NamedTypeSymbol taskAwaiterType ? getResult.OriginalDefinition.AsMember(taskAwaiterType) : getResult; SetResultType(node, reinferredGetResult.ReturnTypeWithAnnotations.ToTypeWithState()); } return result; } public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) { var result = base.VisitTypeOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitMethodInfo(BoundMethodInfo node) { var result = base.VisitMethodInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitFieldInfo(BoundFieldInfo node) { var result = base.VisitFieldInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { // Can occur in error scenarios and lambda scenarios var result = base.VisitDefaultLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); return result; } public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) { Debug.Assert(!this.IsConditionalState); var result = base.VisitDefaultExpression(node); TypeSymbol type = node.Type; if (EmptyStructTypeCache.IsTrackableStructType(type)) { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isDefaultValue: true); } } // https://github.com/dotnet/roslyn/issues/33344: this fails to produce an updated tuple type for a default expression // (should produce nullable element types for those elements that are of reference types) SetResultType(node, TypeWithState.ForType(type)); return result; } public override BoundNode? VisitIsOperator(BoundIsOperator node) { Debug.Assert(!this.IsConditionalState); var operand = node.Operand; var typeExpr = node.TargetType; VisitPossibleConditionalAccess(operand, out var conditionalStateWhenNotNull); Unsplit(); LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean); SetConditionalState(stateWhenNotNull, State); if (typeExpr.Type?.SpecialType == SpecialType.System_Object) { LearnFromNullTest(operand, ref StateWhenFalse); } VisitTypeExpression(typeExpr); SetNotNullResult(node); return null; } public override BoundNode? VisitAsOperator(BoundAsOperator node) { var argumentType = VisitRvalueWithState(node.Operand); NullableFlowState resultState = NullableFlowState.NotNull; var type = node.Type; if (type.CanContainNull()) { switch (node.Conversion.Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: resultState = argumentType.State; break; default: resultState = NullableFlowState.MaybeDefault; break; } } VisitTypeExpression(node.TargetType); SetResultType(node, TypeWithState.Create(type, resultState)); return null; } public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) { var result = base.VisitSizeOfOperator(node); VisitTypeExpression(node.SourceType); SetNotNullResult(node); return result; } public override BoundNode? VisitArgList(BoundArgList node) { var result = base.VisitArgList(node); Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle); SetNotNullResult(node); return result; } public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; } public override BoundNode? VisitLiteral(BoundLiteral node) { Debug.Assert(!IsConditionalState); var result = base.VisitLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, node.Type?.CanContainNull() != false && node.ConstantValue?.IsNull == true ? NullableFlowState.MaybeDefault : NullableFlowState.NotNull)); return result; } public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var result = base.VisitPreviousSubmissionReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { var result = base.VisitHostObjectMemberReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) { var result = base.VisitPseudoVariable(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeExpression(BoundRangeExpression node) { var result = base.VisitRangeExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeVariable(BoundRangeVariable node) { VisitWithoutDiagnostics(node.Value); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Need to review this return null; } public override BoundNode? VisitLabel(BoundLabel node) { var result = base.VisitLabel(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) { var expr = node.Expression; VisitRvalue(expr); // If the expression was a MethodGroup, check nullability of receiver. var receiverOpt = (expr as BoundMethodGroup)?.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { var receiverOpt = node.ReceiverOpt; VisitRvalue(receiverOpt); Debug.Assert(!IsConditionalState); var @event = node.Event; if ([email protected]) { @event = (EventSymbol)AsMemberOfType(ResultType.Type, @event); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); SetUpdatedSymbol(node, node.Event, @event); } VisitRvalue(node.Argument); // https://github.com/dotnet/roslyn/issues/31018: Check for delegate mismatch. if (node.Argument.ConstantValue?.IsNull != true && MakeMemberSlot(receiverOpt, @event) is > 0 and var memberSlot) { this.State[memberSlot] = node.IsAddition ? this.State[memberSlot].Meet(ResultType.State) : NullableFlowState.MaybeNull; } SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29969 Review whether this is the correct result return null; } public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) { var result = base.VisitImplicitReceiver(node); SetNotNullResult(node); return result; } public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { var result = base.VisitNoPiaObjectCreationExpression(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectOrDynamicObjectCreation(node, ImmutableArray<BoundExpression>.Empty, ImmutableArray<VisitArgumentResult>.Empty, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) { var result = base.VisitArrayInitialization(node); SetNotNullResult(node); return result; } private void SetUnknownResultNullability(BoundExpression expression) { SetResultType(expression, TypeWithState.Create(expression.Type, default)); } public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { var result = base.VisitStackAllocArrayCreation(node); Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); SetNotNullResult(node); return result; } public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) { return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) { Debug.Assert(!this.IsConditionalState); bool reportedDiagnostic = false; if (receiverOpt != null && this.State.Reachable) { var resultTypeSymbol = resultType.Type; if (resultTypeSymbol is null) { return false; } #if DEBUG Debug.Assert(receiverOpt.Type is null || AreCloseEnough(receiverOpt.Type, resultTypeSymbol)); #endif if (!ReportPossibleNullReceiverIfNeeded(resultTypeSymbol, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) { return reportedDiagnostic; } LearnFromNonNullTest(receiverOpt, ref this.State); } return reportedDiagnostic; } // Returns false if the type wasn't interesting private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) { reportedDiagnostic = false; if (state.MayBeNull()) { bool isValueType = type.IsValueType; if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) { return false; } ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); reportedDiagnostic = true; } return true; } private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) { VisitArgumentConversionAndInboundAssignmentsAndPreConditions( conversionOpt: null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), stateForLambda: default), extensionMethodThisArgument: true); } private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } public override BoundNode? VisitQueryClause(BoundQueryClause node) { var result = base.VisitQueryClause(node); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Implement nullability analysis in LINQ queries return result; } public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) { var result = base.VisitNameOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) { var result = base.VisitNamespaceExpression(node); SetUnknownResultNullability(node); return result; } // https://github.com/dotnet/roslyn/issues/54583 // Better handle the constructor propagation //public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) //{ //} public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // This is only involved with unbound lambdas or when visiting the source of a converted tuple literal var result = base.VisitUnconvertedInterpolatedString(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitStringInsert(BoundStringInsert node) { var result = base.VisitStringInsert(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { var result = base.VisitConvertedStackAllocExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) { var result = TypeWithAnnotations.Create(node.Type); var rValueType = TypeWithState.ForType(node.Type); SetResult(node, rValueType, result); return null; } public override BoundNode? VisitThrowExpression(BoundThrowExpression node) { VisitThrow(node.Expression); SetResultType(node, default); return null; } public override BoundNode? VisitThrowStatement(BoundThrowStatement node) { VisitThrow(node.ExpressionOpt); return null; } private void VisitThrow(BoundExpression? expr) { if (expr != null) { var result = VisitRvalueWithState(expr); // Cases: // null // null! // Other (typed) expression, including suppressed ones if (result.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); } } SetUnreachable(); } public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundExpression expr = node.Expression; if (expr == null) { return null; } var method = (MethodSymbol)CurrentSymbol; TypeWithAnnotations elementType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, RefKind.None, method.ReturnType, errorLocation: null, diagnostics: null); _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); return null; } protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) { TakeIncrementalSnapshot(node); if (node.Locals.Length > 0) { LocalSymbol local = node.Locals[0]; if (local.DeclarationKind == LocalDeclarationKind.CatchVariable) { int slot = GetOrCreateSlot(local); if (slot > 0) this.State[slot] = NullableFlowState.NotNull; } } if (node.ExceptionSourceOpt != null) { VisitWithoutDiagnostics(node.ExceptionSourceOpt); } base.VisitCatchBlock(node, ref finallyState); } public override BoundNode? VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); _ = CheckPossibleNullReceiver(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode? VisitAttribute(BoundAttribute node) { VisitArguments(node, node.ConstructorArguments, ImmutableArray<RefKind>.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); } SetNotNullResult(node); return null; } public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) { var typeWithAnnotations = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetResult(node.Expression, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { SetNotNullResult(node); return null; } [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] private void EnsureAwaitablePlaceholdersInitialized() { _awaitablePlaceholdersOpt ??= PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>.GetInstance(); } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { SetNotNullResult(node); } return null; } public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) { Visit(node.AwaitableInstancePlaceholder); Visit(node.GetAwaiter); return null; } public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { _ = Visit(node.InvokedExpression); Debug.Assert(ResultType is TypeWithState { Type: FunctionPointerTypeSymbol { }, State: NullableFlowState.NotNull }); _ = VisitArguments( node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); var returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); return null; } protected override string Dump(LocalState state) { return state.Dump(_variables); } protected override bool Meet(ref LocalState self, ref LocalState other) { if (!self.Reachable) return false; if (!other.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Meet(in other); } protected override bool Join(ref LocalState self, ref LocalState other) { if (!other.Reachable) return false; if (!self.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Join(in other); } private void Join(ref PossiblyConditionalState other) { var otherIsConditional = other.IsConditionalState; if (otherIsConditional) { Split(); } if (IsConditionalState) { Join(ref StateWhenTrue, ref otherIsConditional ? ref other.StateWhenTrue : ref other.State); Join(ref StateWhenFalse, ref otherIsConditional ? ref other.StateWhenFalse : ref other.State); } else { Debug.Assert(!otherIsConditional); Join(ref State, ref other.State); } } private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { return conditionalState.State.Clone(); } var state = conditionalState.StateWhenTrue.Clone(); Join(ref state, ref conditionalState.StateWhenFalse); return state; } private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { SetState(conditionalState.State); } else { SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); } } internal sealed class LocalStateSnapshot { internal readonly int Id; internal readonly LocalStateSnapshot? Container; internal readonly BitVector State; internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) { Id = id; Container = container; State = state; } } /// <summary> /// A bit array containing the nullability of variables associated with a method scope. If the method is a /// nested function (a lambda or a local function), there is a reference to the corresponding instance for /// the containing method scope. The instances in the chain are associated with a corresponding /// <see cref="Variables"/> chain, and the <see cref="Id"/> field in this type matches <see cref="Variables.Id"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LocalState : ILocalDataFlowState { private sealed class Boxed { internal LocalState Value; internal Boxed(LocalState value) { Value = value; } } internal readonly int Id; private readonly Boxed? _container; // The representation of a state is a bit vector with two bits per slot: // (false, false) => NotNull, (false, true) => MaybeNull, (true, true) => MaybeDefault. // Slot 0 is used to represent whether the state is reachable (true) or not. private BitVector _state; private LocalState(int id, Boxed? container, BitVector state) { Id = id; _container = container; _state = state; } internal static LocalState Create(LocalStateSnapshot snapshot) { var container = snapshot.Container is null ? null : new Boxed(Create(snapshot.Container)); return new LocalState(snapshot.Id, container, snapshot.State.Clone()); } internal LocalStateSnapshot CreateSnapshot() { return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), _state.Clone()); } public bool Reachable => _state[0]; public bool NormalizeToBottom => false; public static LocalState ReachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: true); } public static LocalState UnreachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: false); } private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) { var container = variables.Container is null ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable)); int capacity = reachable ? variables.NextAvailableIndex : 1; return new LocalState(variables.Id, container, CreateBitVector(capacity, reachable)); } public LocalState CreateNestedMethodState(Variables variables) { Debug.Assert(Id == variables.Container!.Id); return new LocalState(variables.Id, container: new Boxed(this), CreateBitVector(capacity: variables.NextAvailableIndex, reachable: true)); } private static BitVector CreateBitVector(int capacity, bool reachable) { if (capacity < 1) capacity = 1; BitVector state = BitVector.Create(capacity * 2); state[0] = reachable; return state; } private int Capacity => _state.Capacity / 2; private void EnsureCapacity(int capacity) { _state.EnsureCapacity(capacity * 2); } public bool HasVariable(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasVariable(id, index); } private bool HasVariable(int id, int index) { if (Id > id) { return _container!.Value.HasValue(id, index); } else { return Id == id; } } public bool HasValue(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasValue(id, index); } private bool HasValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.HasValue(id, index); } else { return index < Capacity; } } public void Normalize(NullableWalker walker, Variables variables) { if (Id != variables.Id) { Debug.Assert(Id < variables.Id); Normalize(walker, variables.Container!); } else { _container?.Value.Normalize(walker, variables.Container!); int start = Capacity; EnsureCapacity(variables.NextAvailableIndex); Populate(walker, start); } } public void PopulateAll(NullableWalker walker) { _container?.Value.PopulateAll(walker); Populate(walker, start: 1); } private void Populate(NullableWalker walker, int start) { int capacity = Capacity; for (int index = start; index < capacity; index++) { int slot = Variables.ConstructSlot(Id, index); SetValue(Id, index, walker.GetDefaultState(ref this, slot)); } } public NullableFlowState this[int slot] { get { (int id, int index) = Variables.DeconstructSlot(slot); return GetValue(id, index); } set { (int id, int index) = Variables.DeconstructSlot(slot); SetValue(id, index, value); } } private NullableFlowState GetValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.GetValue(id, index); } else { if (index < Capacity && this.Reachable) { index *= 2; var result = (_state[index + 1], _state[index]) switch { (false, false) => NullableFlowState.NotNull, (false, true) => NullableFlowState.MaybeNull, (true, false) => throw ExceptionUtilities.UnexpectedValue(index), (true, true) => NullableFlowState.MaybeDefault }; return result; } return NullableFlowState.NotNull; } } private void SetValue(int id, int index, NullableFlowState value) { if (Id != id) { Debug.Assert(Id > id); _container!.Value.SetValue(id, index, value); } else { // No states should be modified in unreachable code, as there is only one unreachable state. if (!this.Reachable) return; index *= 2; _state[index] = (value != NullableFlowState.NotNull); _state[index + 1] = (value == NullableFlowState.MaybeDefault); } } internal void ForEach<TArg>(Action<int, TArg> action, TArg arg) { _container?.Value.ForEach(action, arg); for (int index = 1; index < Capacity; index++) { action(Variables.ConstructSlot(Id, index), arg); } } internal LocalState GetStateForVariables(int id) { var state = this; while (state.Id != id) { state = state._container!.Value; } return state; } /// <summary> /// Produce a duplicate of this flow analysis state. /// </summary> /// <returns></returns> public LocalState Clone() { var container = _container is null ? null : new Boxed(_container.Value.Clone()); return new LocalState(Id, container, _state.Clone()); } public bool Join(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Join(in other._container!.Value)) { result = true; } if (_state.UnionWith(in other._state)) { result = true; } return result; } public bool Meet(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Meet(in other._container!.Value)) { result = true; } if (_state.IntersectWith(in other._state)) { result = true; } return result; } internal string GetDebuggerDisplay() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(" "); int n = Math.Min(Capacity, 8); for (int i = n - 1; i >= 0; i--) builder.Append(_state[i * 2] ? '?' : '!'); return pooledBuilder.ToStringAndFree(); } internal string Dump(Variables variables) { if (!this.Reachable) return "unreachable"; if (Id != variables.Id) return "invalid"; var builder = PooledStringBuilder.GetInstance(); Dump(builder, variables); return builder.ToStringAndFree(); } private void Dump(StringBuilder builder, Variables variables) { _container?.Value.Dump(builder, variables.Container!); for (int index = 1; index < Capacity; index++) { if (getName(Variables.ConstructSlot(Id, index)) is string name) { builder.Append(name); var annotation = GetValue(Id, index) switch { NullableFlowState.MaybeNull => "?", NullableFlowState.MaybeDefault => "??", _ => "!" }; builder.Append(annotation); } } string? getName(int slot) { VariableIdentifier id = variables[slot]; var name = id.Symbol.Name; int containingSlot = id.ContainingSlot; return containingSlot > 0 ? getName(containingSlot) + "." + name : name; } } } internal sealed class LocalFunctionState : AbstractLocalFunctionState { /// <summary> /// Defines the starting state used in the local function body to /// produce diagnostics and determine types. /// </summary> public LocalState StartingState; public LocalFunctionState(LocalState unreachableState) : base(unreachableState.Clone(), unreachableState.Clone()) { StartingState = unreachableState; } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) { var variables = (symbol.ContainingSymbol is MethodSymbol containingMethod ? _variables.GetVariablesForMethodScope(containingMethod) : null) ?? _variables.GetRootScope(); return new LocalFunctionState(LocalState.UnreachableState(variables)); } private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> { public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) { return x.info.Equals(y.info) && Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); } public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) { return obj.GetHashCode(); } } private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> { internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); private ExpressionAndSymbolEqualityComparer() { } public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) { RoslynDebug.Assert(x.symbol is object); RoslynDebug.Assert(y.symbol is object); // We specifically use reference equality for the symbols here because the BoundNode should be immutable. // We should be storing and retrieving the exact same instance of the symbol, not just an "equivalent" // symbol. return x.expr == y.expr && (object)x.symbol == y.symbol; } public int GetHashCode((BoundNode? expr, Symbol symbol) obj) { RoslynDebug.Assert(obj.symbol is object); return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); } } } }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_BinaryOperator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { return VisitBinaryOperator(node, null); } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { // Yes, we could have a lifted, logical, user-defined operator: // // struct C { // public static C operator &(C x, C y) {...} // public static bool operator true(C? c) { ... } // public static bool operator false(C? c) { ... } // } // // If we have C? q, r and we say q && r then this gets bound as // C? tempQ = q ; // C.false(tempQ) ? // tempQ : // ( // C? tempR = r ; // tempQ.HasValue & tempR.HasValue ? // new C?(C.&(tempQ.GetValueOrDefault(), tempR.GetValueOrDefault())) : // default C?() // ) // // Note that the native compiler does not allow q && r. However, the native compiler // *does* allow q && r if C is defined as: // // struct C { // public static C? operator &(C? x, C? y) {...} // public static bool operator true(C? c) { ... } // public static bool operator false(C? c) { ... } // } // // It seems unusual and wrong that an & operator should be allowed to become // a && operator if there is a "manually lifted" operator in source, but not // if there is a "synthesized" lifted operator. Roslyn fixes this bug. // // Anyway, in this case we must lower this to its non-logical form, and then // lower the interior of that to its non-lifted form. // See comments in method IsValidUserDefinedConditionalLogicalOperator for information // on some subtle aspects of this lowering. // We generate one of: // // x || y --> temp = x; T.true(temp) ? temp : T.|(temp, y); // x && y --> temp = x; T.false(temp) ? temp : T.&(temp, y); // // For the ease of naming locals, we'll assume we're doing an &&. // TODO: We generate every one of these as "temp = x; T.false(temp) ? temp : T.&(temp, y)" even // TODO: when x has no side effects. We can optimize away the temporary if there are no side effects. var syntax = node.Syntax; var operatorKind = node.OperatorKind; var type = node.Type; BoundExpression loweredLeft = VisitExpression(node.Left); BoundExpression loweredRight = VisitExpression(node.Right); if (_inExpressionLambda) { return node.Update(operatorKind, node.LogicalOperator, node.TrueOperator, node.FalseOperator, node.ConstrainedToTypeOpt, node.ResultKind, loweredLeft, loweredRight, type); } BoundAssignmentOperator tempAssignment; var boundTemp = _factory.StoreToTemp(loweredLeft, out tempAssignment); // T.false(temp) var falseOperatorCall = BoundCall.Synthesized(syntax, receiverOpt: node.ConstrainedToTypeOpt is null ? null : new BoundTypeExpression(syntax, aliasOpt: null, node.ConstrainedToTypeOpt), operatorKind.Operator() == BinaryOperatorKind.And ? node.FalseOperator : node.TrueOperator, boundTemp); // T.&(temp, y) var andOperatorCall = LowerUserDefinedBinaryOperator(syntax, operatorKind & ~BinaryOperatorKind.Logical, boundTemp, loweredRight, type, node.LogicalOperator, node.ConstrainedToTypeOpt); // T.false(temp) ? temp : T.&(temp, y) BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: falseOperatorCall, rewrittenConsequence: boundTemp, rewrittenAlternative: andOperatorCall, constantValueOpt: null, rewrittenType: type, isRef: false); // temp = x; T.false(temp) ? temp : T.&(temp, y) return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create(boundTemp.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment), value: conditionalExpression, type: type); } public BoundExpression VisitBinaryOperator(BoundBinaryOperator node, BoundUnaryOperator? applyParentUnaryOperator) { if (node.InterpolatedStringHandlerData is InterpolatedStringHandlerData data) { Debug.Assert(node.Type.SpecialType == SpecialType.System_String, "Non-string binary addition should have been handled by VisitConversion or VisitArguments"); ImmutableArray<BoundExpression> parts = CollectBinaryOperatorInterpolatedStringParts(node); return LowerPartsToString(data, parts, node.Syntax, node.Type); } // In machine-generated code we frequently end up with binary operator trees that are deep on the left, // such as a + b + c + d ... // To avoid blowing the call stack, we make an explicit stack of the binary operators to the left, // and then lower by traversing the explicit stack. var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); for (BoundBinaryOperator? current = node; current != null && current.ConstantValue == null; current = current.Left as BoundBinaryOperator) { // The regular visit mechanism will handle this. if (current.InterpolatedStringHandlerData is not null) { Debug.Assert(stack.Count >= 1); break; } stack.Push(current); } BoundExpression loweredLeft = VisitExpression(stack.Peek().Left); while (stack.Count > 0) { BoundBinaryOperator original = stack.Pop(); BoundExpression loweredRight = VisitExpression(original.Right); loweredLeft = MakeBinaryOperator(original, original.Syntax, original.OperatorKind, loweredLeft, loweredRight, original.Type, original.Method, original.ConstrainedToType, applyParentUnaryOperator: (stack.Count == 0) ? applyParentUnaryOperator : null); } stack.Free(); return loweredLeft; } private static ImmutableArray<BoundExpression> CollectBinaryOperatorInterpolatedStringParts(BoundBinaryOperator node) { Debug.Assert(node.OperatorKind == BinaryOperatorKind.StringConcatenation); Debug.Assert(node.InterpolatedStringHandlerData is not null); var partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(); while (true) { addReversedParts((BoundInterpolatedString)node.Right); if (node.Left is BoundBinaryOperator next) { node = next; } else { addReversedParts((BoundInterpolatedString)node.Left); break; } } partsBuilder.ReverseContents(); ImmutableArray<BoundExpression> parts = partsBuilder.ToImmutableAndFree(); return parts; void addReversedParts(BoundInterpolatedString boundInterpolated) { for (int i = boundInterpolated.Parts.Length - 1; i >= 0; i--) { partsBuilder.Add(boundInterpolated.Parts[i]); } } } private BoundExpression MakeBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, bool isPointerElementAccess = false, bool isCompoundAssignment = false, BoundUnaryOperator? applyParentUnaryOperator = null) { return MakeBinaryOperator(null, syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt, isPointerElementAccess, isCompoundAssignment, applyParentUnaryOperator); } private BoundExpression MakeBinaryOperator( BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, bool isPointerElementAccess = false, bool isCompoundAssignment = false, BoundUnaryOperator? applyParentUnaryOperator = null) { Debug.Assert(oldNode == null || (oldNode.Syntax == syntax)); if (_inExpressionLambda) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.ObjectAndStringConcatenation: case BinaryOperatorKind.StringAndObjectConcatenation: case BinaryOperatorKind.StringConcatenation: return RewriteStringConcatenation(syntax, operatorKind, loweredLeft, loweredRight, type); case BinaryOperatorKind.DelegateCombination: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__Combine); case BinaryOperatorKind.DelegateRemoval: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__Remove); case BinaryOperatorKind.DelegateEqual: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__op_Equality); case BinaryOperatorKind.DelegateNotEqual: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__op_Inequality); } } else // try to lower the expression. { if (operatorKind.IsDynamic()) { Debug.Assert(!isPointerElementAccess); if (operatorKind.IsLogical()) { return MakeDynamicLogicalBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, method, constrainedToTypeOpt, type, isCompoundAssignment, applyParentUnaryOperator); } else { Debug.Assert(method is null); return _dynamicFactory.MakeDynamicBinaryOperator(operatorKind, loweredLeft, loweredRight, isCompoundAssignment, type).ToExpression(); } } if (operatorKind.IsLifted()) { return RewriteLiftedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); } if (operatorKind.IsUserDefined()) { return LowerUserDefinedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); } switch (operatorKind.OperatorWithLogical() | operatorKind.OperandTypes()) { case BinaryOperatorKind.NullableNullEqual: case BinaryOperatorKind.NullableNullNotEqual: return RewriteNullableNullEquality(syntax, operatorKind, loweredLeft, loweredRight, type); case BinaryOperatorKind.ObjectAndStringConcatenation: case BinaryOperatorKind.StringAndObjectConcatenation: case BinaryOperatorKind.StringConcatenation: return RewriteStringConcatenation(syntax, operatorKind, loweredLeft, loweredRight, type); case BinaryOperatorKind.StringEqual: return RewriteStringEquality(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_String__op_Equality); case BinaryOperatorKind.StringNotEqual: return RewriteStringEquality(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_String__op_Inequality); case BinaryOperatorKind.DelegateCombination: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__Combine); case BinaryOperatorKind.DelegateRemoval: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__Remove); case BinaryOperatorKind.DelegateEqual: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__op_Equality); case BinaryOperatorKind.DelegateNotEqual: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__op_Inequality); case BinaryOperatorKind.LogicalBoolAnd: if (loweredRight.ConstantValue == ConstantValue.True) return loweredLeft; if (loweredLeft.ConstantValue == ConstantValue.True) return loweredRight; if (loweredLeft.ConstantValue == ConstantValue.False) return loweredLeft; if (loweredRight.Kind == BoundKind.Local || loweredRight.Kind == BoundKind.Parameter) { operatorKind &= ~BinaryOperatorKind.Logical; } goto default; case BinaryOperatorKind.LogicalBoolOr: if (loweredRight.ConstantValue == ConstantValue.False) return loweredLeft; if (loweredLeft.ConstantValue == ConstantValue.False) return loweredRight; if (loweredLeft.ConstantValue == ConstantValue.True) return loweredLeft; if (loweredRight.Kind == BoundKind.Local || loweredRight.Kind == BoundKind.Parameter) { operatorKind &= ~BinaryOperatorKind.Logical; } goto default; case BinaryOperatorKind.BoolAnd: if (loweredRight.ConstantValue == ConstantValue.True) return loweredLeft; if (loweredLeft.ConstantValue == ConstantValue.True) return loweredRight; // Note that we are using IsDefaultValue instead of False. // That is just to catch cases like default(bool) or others resulting in // a default bool value, that we know to be "false" // bool? generally should not reach here, since it is handled by RewriteLiftedBinaryOperator. // Regardless, the following code should handle default(bool?) correctly since // default(bool?) & <expr> == default(bool?) with sideeffects of <expr> if (loweredLeft.IsDefaultValue()) { return _factory.MakeSequence(loweredRight, loweredLeft); } if (loweredRight.IsDefaultValue()) { return _factory.MakeSequence(loweredLeft, loweredRight); } goto default; case BinaryOperatorKind.BoolOr: if (loweredRight.ConstantValue == ConstantValue.False) return loweredLeft; if (loweredLeft.ConstantValue == ConstantValue.False) return loweredRight; goto default; case BinaryOperatorKind.BoolEqual: if (loweredLeft.ConstantValue == ConstantValue.True) return loweredRight; if (loweredRight.ConstantValue == ConstantValue.True) return loweredLeft; Debug.Assert(loweredLeft.Type is { }); Debug.Assert(loweredRight.Type is { }); if (loweredLeft.ConstantValue == ConstantValue.False) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredRight, loweredRight.Type); if (loweredRight.ConstantValue == ConstantValue.False) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredLeft, loweredLeft.Type); goto default; case BinaryOperatorKind.BoolNotEqual: if (loweredLeft.ConstantValue == ConstantValue.False) return loweredRight; if (loweredRight.ConstantValue == ConstantValue.False) return loweredLeft; Debug.Assert(loweredLeft.Type is { }); Debug.Assert(loweredRight.Type is { }); if (loweredLeft.ConstantValue == ConstantValue.True) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredRight, loweredRight.Type); if (loweredRight.ConstantValue == ConstantValue.True) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredLeft, loweredLeft.Type); goto default; case BinaryOperatorKind.BoolXor: if (loweredLeft.ConstantValue == ConstantValue.False) return loweredRight; if (loweredRight.ConstantValue == ConstantValue.False) return loweredLeft; Debug.Assert(loweredLeft.Type is { }); Debug.Assert(loweredRight.Type is { }); if (loweredLeft.ConstantValue == ConstantValue.True) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredRight, loweredRight.Type); if (loweredRight.ConstantValue == ConstantValue.True) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredLeft, loweredLeft.Type); goto default; case BinaryOperatorKind.IntLeftShift: case BinaryOperatorKind.UIntLeftShift: case BinaryOperatorKind.IntRightShift: case BinaryOperatorKind.UIntRightShift: return RewriteBuiltInShiftOperation(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, 0x1F); case BinaryOperatorKind.LongLeftShift: case BinaryOperatorKind.ULongLeftShift: case BinaryOperatorKind.LongRightShift: case BinaryOperatorKind.ULongRightShift: return RewriteBuiltInShiftOperation(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, 0x3F); case BinaryOperatorKind.DecimalAddition: case BinaryOperatorKind.DecimalSubtraction: case BinaryOperatorKind.DecimalMultiplication: case BinaryOperatorKind.DecimalDivision: case BinaryOperatorKind.DecimalRemainder: case BinaryOperatorKind.DecimalEqual: case BinaryOperatorKind.DecimalNotEqual: case BinaryOperatorKind.DecimalLessThan: case BinaryOperatorKind.DecimalLessThanOrEqual: case BinaryOperatorKind.DecimalGreaterThan: case BinaryOperatorKind.DecimalGreaterThanOrEqual: return RewriteDecimalBinaryOperation(syntax, loweredLeft, loweredRight, operatorKind); case BinaryOperatorKind.PointerAndIntAddition: case BinaryOperatorKind.PointerAndUIntAddition: case BinaryOperatorKind.PointerAndLongAddition: case BinaryOperatorKind.PointerAndULongAddition: case BinaryOperatorKind.PointerAndIntSubtraction: case BinaryOperatorKind.PointerAndUIntSubtraction: case BinaryOperatorKind.PointerAndLongSubtraction: case BinaryOperatorKind.PointerAndULongSubtraction: if (loweredRight.IsDefaultValue()) { return loweredLeft; } return RewritePointerNumericOperator(syntax, operatorKind, loweredLeft, loweredRight, type, isPointerElementAccess, isLeftPointer: true); case BinaryOperatorKind.IntAndPointerAddition: case BinaryOperatorKind.UIntAndPointerAddition: case BinaryOperatorKind.LongAndPointerAddition: case BinaryOperatorKind.ULongAndPointerAddition: if (loweredLeft.IsDefaultValue()) { return loweredRight; } return RewritePointerNumericOperator(syntax, operatorKind, loweredLeft, loweredRight, type, isPointerElementAccess, isLeftPointer: false); case BinaryOperatorKind.PointerSubtraction: return RewritePointerSubtraction(operatorKind, loweredLeft, loweredRight, type); case BinaryOperatorKind.IntAddition: case BinaryOperatorKind.UIntAddition: case BinaryOperatorKind.LongAddition: case BinaryOperatorKind.ULongAddition: if (loweredLeft.IsDefaultValue()) { return loweredRight; } if (loweredRight.IsDefaultValue()) { return loweredLeft; } goto default; case BinaryOperatorKind.IntSubtraction: case BinaryOperatorKind.LongSubtraction: case BinaryOperatorKind.UIntSubtraction: case BinaryOperatorKind.ULongSubtraction: if (loweredRight.IsDefaultValue()) { return loweredLeft; } goto default; case BinaryOperatorKind.IntMultiplication: case BinaryOperatorKind.LongMultiplication: case BinaryOperatorKind.UIntMultiplication: case BinaryOperatorKind.ULongMultiplication: if (loweredLeft.IsDefaultValue()) { return _factory.MakeSequence(loweredRight, loweredLeft); } if (loweredRight.IsDefaultValue()) { return _factory.MakeSequence(loweredLeft, loweredRight); } if (loweredLeft.ConstantValue?.UInt64Value == 1) { return loweredRight; } if (loweredRight.ConstantValue?.UInt64Value == 1) { return loweredLeft; } goto default; case BinaryOperatorKind.IntGreaterThan: case BinaryOperatorKind.IntLessThanOrEqual: if (loweredLeft.Kind == BoundKind.ArrayLength && loweredRight.IsDefaultValue()) { //array length is never negative var newOp = operatorKind == BinaryOperatorKind.IntGreaterThan ? BinaryOperatorKind.NotEqual : BinaryOperatorKind.Equal; operatorKind &= ~BinaryOperatorKind.OpMask; operatorKind |= newOp; loweredLeft = UnconvertArrayLength((BoundArrayLength)loweredLeft); } goto default; case BinaryOperatorKind.IntLessThan: case BinaryOperatorKind.IntGreaterThanOrEqual: if (loweredRight.Kind == BoundKind.ArrayLength && loweredLeft.IsDefaultValue()) { //array length is never negative var newOp = operatorKind == BinaryOperatorKind.IntLessThan ? BinaryOperatorKind.NotEqual : BinaryOperatorKind.Equal; operatorKind &= ~BinaryOperatorKind.OpMask; operatorKind |= newOp; loweredRight = UnconvertArrayLength((BoundArrayLength)loweredRight); } goto default; case BinaryOperatorKind.IntEqual: case BinaryOperatorKind.IntNotEqual: if (loweredLeft.Kind == BoundKind.ArrayLength && loweredRight.IsDefaultValue()) { loweredLeft = UnconvertArrayLength((BoundArrayLength)loweredLeft); } else if (loweredRight.Kind == BoundKind.ArrayLength && loweredLeft.IsDefaultValue()) { loweredRight = UnconvertArrayLength((BoundArrayLength)loweredRight); } goto default; default: break; } } return (oldNode != null) ? oldNode.Update(operatorKind, oldNode.ConstantValue, oldNode.Method, oldNode.ConstrainedToType, oldNode.ResultKind, loweredLeft, loweredRight, type) : new BoundBinaryOperator(syntax, operatorKind, constantValueOpt: null, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, loweredLeft, loweredRight, type); } private BoundExpression RewriteLiftedBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { var conditionalLeft = loweredLeft as BoundLoweredConditionalAccess; // NOTE: we could in theory handle side-effecting loweredRight here too // by including it as a part of whenNull, but there is a concern // that it can lead to code duplication var optimize = conditionalLeft != null && operatorKind != BinaryOperatorKind.LiftedBoolOr && operatorKind != BinaryOperatorKind.LiftedBoolAnd && !ReadIsSideeffecting(loweredRight) && (conditionalLeft.WhenNullOpt == null || conditionalLeft.WhenNullOpt.IsDefaultValue()); if (optimize) { loweredLeft = conditionalLeft!.WhenNotNull; } var result = operatorKind.IsComparison() ? operatorKind.IsUserDefined() ? LowerLiftedUserDefinedComparisonOperator(syntax, operatorKind, loweredLeft, loweredRight, method, constrainedToTypeOpt) : LowerLiftedBuiltInComparisonOperator(syntax, operatorKind, loweredLeft, loweredRight) : LowerLiftedBinaryArithmeticOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); if (optimize) { BoundExpression? whenNullOpt = null; // for all operators null-in means null-out // except for the Equal/NotEqual since null == null ==> true if (operatorKind.Operator() == BinaryOperatorKind.NotEqual || operatorKind.Operator() == BinaryOperatorKind.Equal) { Debug.Assert(loweredLeft.Type is { }); whenNullOpt = RewriteLiftedBinaryOperator(syntax, operatorKind, _factory.Default(loweredLeft.Type), loweredRight, type, method, constrainedToTypeOpt); } result = conditionalLeft!.Update( conditionalLeft.Receiver, conditionalLeft.HasValueMethodOpt, whenNotNull: result, whenNullOpt: whenNullOpt, id: conditionalLeft.Id, type: result.Type! ); } return result; } //array length produces native uint, so the node typically implies a conversion to int32/int64. //Sometimes the conversion is not necessary - i.e. when we just check for 0 //This helper removes unnecessary implied conversion from ArrayLength node. private BoundExpression UnconvertArrayLength(BoundArrayLength arrLength) { return arrLength.Update(arrLength.Expression, _factory.SpecialType(SpecialType.System_UIntPtr)); } private BoundExpression MakeDynamicLogicalBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, MethodSymbol? leftTruthOperator, TypeSymbol? constrainedToTypeOpt, TypeSymbol type, bool isCompoundAssignment, BoundUnaryOperator? applyParentUnaryOperator) { Debug.Assert(operatorKind.Operator() == BinaryOperatorKind.And || operatorKind.Operator() == BinaryOperatorKind.Or); // Dynamic logical && and || operators are lowered as follows: // left && right -> IsFalse(left) ? left : And(left, right) // left || right -> IsTrue(left) ? left : Or(left, right) // // Optimization: If the binary AND/OR is directly contained in IsFalse/IsTrue operator (parentUnaryOperator != null) // we can avoid calling IsFalse/IsTrue twice on the same object. // IsFalse(left && right) -> IsFalse(left) || IsFalse(And(left, right)) // IsTrue(left || right) -> IsTrue(left) || IsTrue(Or(left, right)) bool isAnd = operatorKind.Operator() == BinaryOperatorKind.And; // Operator to be used to test the left operand: var testOperator = isAnd ? UnaryOperatorKind.DynamicFalse : UnaryOperatorKind.DynamicTrue; // VisitUnaryOperator ensures we are never called with parentUnaryOperator != null when we can't perform the optimization. Debug.Assert(applyParentUnaryOperator == null || applyParentUnaryOperator.OperatorKind == testOperator); ConstantValue? constantLeft = loweredLeft.ConstantValue ?? UnboxConstant(loweredLeft); if (testOperator == UnaryOperatorKind.DynamicFalse && constantLeft == ConstantValue.False || testOperator == UnaryOperatorKind.DynamicTrue && constantLeft == ConstantValue.True) { Debug.Assert(leftTruthOperator == null); if (applyParentUnaryOperator != null) { // IsFalse(false && right) -> true // IsTrue(true || right) -> true return _factory.Literal(true); } else { // false && right -> box(false) // true || right -> box(true) return MakeConversionNode(loweredLeft, type, @checked: false); } } BoundExpression result; var boolean = _compilation.GetSpecialType(SpecialType.System_Boolean); // Store left to local if needed. If constant or already local we don't need a temp // since the value of left can't change until right is evaluated. BoundAssignmentOperator? tempAssignment; BoundLocal? temp; if (constantLeft == null && loweredLeft.Kind != BoundKind.Local && loweredLeft.Kind != BoundKind.Parameter) { BoundAssignmentOperator assignment; var local = _factory.StoreToTemp(loweredLeft, out assignment); loweredLeft = local; tempAssignment = assignment; temp = local; } else { tempAssignment = null; temp = null; } var op = _dynamicFactory.MakeDynamicBinaryOperator(operatorKind, loweredLeft, loweredRight, isCompoundAssignment, type).ToExpression(); // IsFalse(true) or IsTrue(false) are always false: bool leftTestIsConstantFalse = testOperator == UnaryOperatorKind.DynamicFalse && constantLeft == ConstantValue.True || testOperator == UnaryOperatorKind.DynamicTrue && constantLeft == ConstantValue.False; if (applyParentUnaryOperator != null) { // IsFalse(left && right) -> IsFalse(left) || IsFalse(And(left, right)) // IsTrue(left || right) -> IsTrue(left) || IsTrue(Or(left, right)) result = _dynamicFactory.MakeDynamicUnaryOperator(testOperator, op, boolean).ToExpression(); if (!leftTestIsConstantFalse) { BoundExpression leftTest = MakeTruthTestForDynamicLogicalOperator(syntax, loweredLeft, boolean, leftTruthOperator, constrainedToTypeOpt, negative: isAnd); result = _factory.Binary(BinaryOperatorKind.LogicalOr, boolean, leftTest, result); } } else { // left && right -> IsFalse(left) ? left : And(left, right) // left || right -> IsTrue(left) ? left : Or(left, right) if (leftTestIsConstantFalse) { result = op; } else { // We might need to box. BoundExpression leftTest = MakeTruthTestForDynamicLogicalOperator(syntax, loweredLeft, boolean, leftTruthOperator, constrainedToTypeOpt, negative: isAnd); var convertedLeft = MakeConversionNode(loweredLeft, type, @checked: false); result = _factory.Conditional(leftTest, convertedLeft, op, type); } } if (tempAssignment != null) { Debug.Assert(temp is { }); return _factory.Sequence(ImmutableArray.Create(temp.LocalSymbol), ImmutableArray.Create<BoundExpression>(tempAssignment), result); } return result; } private static ConstantValue? UnboxConstant(BoundExpression expression) { if (expression.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)expression; if (conversion.ConversionKind == ConversionKind.Boxing) { return conversion.Operand.ConstantValue; } } return null; } private BoundExpression MakeTruthTestForDynamicLogicalOperator(SyntaxNode syntax, BoundExpression loweredLeft, TypeSymbol boolean, MethodSymbol? leftTruthOperator, TypeSymbol? constrainedToTypeOpt, bool negative) { if (loweredLeft.HasDynamicType()) { Debug.Assert(leftTruthOperator == null); return _dynamicFactory.MakeDynamicUnaryOperator(negative ? UnaryOperatorKind.DynamicFalse : UnaryOperatorKind.DynamicTrue, loweredLeft, boolean).ToExpression(); } // Although the spec doesn't capture it we do the same that Dev11 does: // Use implicit conversion to Boolean if it is defined on the static type of the left operand. // If not the type has to implement IsTrue/IsFalse operator - we checked it during binding. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(); var conversion = _compilation.Conversions.ClassifyConversionFromExpression(loweredLeft, boolean, ref useSiteInfo); _diagnostics.Add(loweredLeft.Syntax, useSiteInfo); if (conversion.IsImplicit) { Debug.Assert(leftTruthOperator == null); var converted = MakeConversionNode(loweredLeft, boolean, @checked: false); if (negative) { return new BoundUnaryOperator(syntax, UnaryOperatorKind.BoolLogicalNegation, converted, ConstantValue.NotAvailable, MethodSymbol.None, constrainedToTypeOpt: null, LookupResultKind.Viable, boolean) { WasCompilerGenerated = true }; } else { return converted; } } Debug.Assert(leftTruthOperator != null); return BoundCall.Synthesized(syntax, receiverOpt: constrainedToTypeOpt is null ? null : new BoundTypeExpression(syntax, aliasOpt: null, constrainedToTypeOpt), leftTruthOperator, loweredLeft); } private BoundExpression LowerUserDefinedBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { Debug.Assert(!operatorKind.IsLogical()); if (operatorKind.IsLifted()) { return RewriteLiftedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); } // Otherwise, nothing special here. Debug.Assert(method is { }); Debug.Assert(TypeSymbol.Equals(method.ReturnType, type, TypeCompareKind.ConsiderEverything2)); return BoundCall.Synthesized(syntax, receiverOpt: constrainedToTypeOpt is null ? null : new BoundTypeExpression(syntax, aliasOpt: null, constrainedToTypeOpt), method, loweredLeft, loweredRight); } private BoundExpression? TrivialLiftedComparisonOperatorOptimizations( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { Debug.Assert(left != null); Debug.Assert(right != null); // Optimization #1: if both sides are null then the result // is either true (for equality) or false (for everything else.) bool leftAlwaysNull = NullableNeverHasValue(left); bool rightAlwaysNull = NullableNeverHasValue(right); TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); if (leftAlwaysNull && rightAlwaysNull) { return MakeLiteral(syntax, ConstantValue.Create(kind.Operator() == BinaryOperatorKind.Equal), boolType); } // Optimization #2: If both sides are non-null then we can again eliminate the lifting entirely. BoundExpression? leftNonNull = NullableAlwaysHasValue(left); BoundExpression? rightNonNull = NullableAlwaysHasValue(right); if (leftNonNull != null && rightNonNull != null) { return MakeBinaryOperator( syntax: syntax, operatorKind: kind.Unlifted(), loweredLeft: leftNonNull, loweredRight: rightNonNull, type: boolType, method: method, constrainedToTypeOpt: constrainedToTypeOpt); } // Optimization #3: If one side is null and the other is definitely not, then we generate the side effects // of the non-null side and result in true (for not-equals) or false (for everything else.) BinaryOperatorKind operatorKind = kind.Operator(); if (leftAlwaysNull && rightNonNull != null || rightAlwaysNull && leftNonNull != null) { BoundExpression result = MakeLiteral(syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.NotEqual), boolType); BoundExpression? nonNull = leftAlwaysNull ? rightNonNull : leftNonNull; Debug.Assert(nonNull is { }); if (ReadIsSideeffecting(nonNull)) { result = new BoundSequence( syntax: syntax, locals: ImmutableArray<LocalSymbol>.Empty, sideEffects: ImmutableArray.Create<BoundExpression>(nonNull), value: result, type: boolType); } return result; } // Optimization #4: If one side is null and the other is unknown, then we have three cases: // #4a: If we have x == null then that becomes !x.HasValue. // #4b: If we have x != null then that becomes x.HasValue. // #4c: If we have x OP null then that becomes side effects of x, result in false. if (leftAlwaysNull || rightAlwaysNull) { BoundExpression maybeNull = leftAlwaysNull ? right : left; if (operatorKind == BinaryOperatorKind.Equal || operatorKind == BinaryOperatorKind.NotEqual) { BoundExpression callHasValue = MakeNullableHasValue(syntax, maybeNull); BoundExpression result = operatorKind == BinaryOperatorKind.Equal ? MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, callHasValue, boolType) : callHasValue; return result; } else { BoundExpression falseExpr = MakeBooleanConstant(syntax, operatorKind == BinaryOperatorKind.NotEqual); return _factory.MakeSequence(maybeNull, falseExpr); } } return null; } private BoundExpression MakeOptimizedGetValueOrDefault(SyntaxNode syntax, BoundExpression expression) { Debug.Assert(expression.Type is { }); // If the expression is of nullable type then call GetValueOrDefault. If not, // then just use its value. if (expression.Type.IsNullableType()) { return BoundCall.Synthesized(syntax, expression, UnsafeGetNullableMethod(syntax, expression.Type, SpecialMember.System_Nullable_T_GetValueOrDefault)); } return expression; } private BoundExpression MakeBooleanConstant(SyntaxNode syntax, bool value) { return MakeLiteral(syntax, ConstantValue.Create(value), _compilation.GetSpecialType(SpecialType.System_Boolean)); } private BoundExpression MakeOptimizedHasValue(SyntaxNode syntax, BoundExpression expression) { Debug.Assert(expression.Type is { }); // If the expression is of nullable type then call HasValue. If not, then it has a value, // so return constant true. if (expression.Type.IsNullableType()) { return MakeNullableHasValue(syntax, expression); } return MakeBooleanConstant(syntax, true); } private BoundExpression MakeNullableHasValue(SyntaxNode syntax, BoundExpression expression) { Debug.Assert(expression.Type is { }); return BoundCall.Synthesized(syntax, expression, UnsafeGetNullableMethod(syntax, expression.Type, SpecialMember.System_Nullable_T_get_HasValue)); } private BoundExpression LowerLiftedBuiltInComparisonOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight) { // SPEC: For the equality operators == != : // SPEC: The lifted operator considers two null values equal and a null value unequal to // SPEC: any non-null value. If both operands are non-null the lifted operator unwraps // SPEC: the operands and applies the underlying operator to produce the bool result. // SPEC: // SPEC: For the relational operators < > <= >= : // SPEC: The lifted operator produces the value false if one or both operands // SPEC: are null. Otherwise the lifted operator unwraps the operands and // SPEC: applies the underlying operator to produce the bool result. // Note that this means that x == y is true but x <= y is false if both are null. // x <= y is not the same as (x < y) || (x == y). // Start with some simple optimizations for cases like one side being null. BoundExpression? optimized = TrivialLiftedComparisonOperatorOptimizations(syntax, kind, loweredLeft, loweredRight, method: null, constrainedToTypeOpt: null); if (optimized != null) { return optimized; } // We rewrite x == y as // // tempx = x; // tempy = y; // result = (tempx.GetValueOrDefault() == tempy.GetValueOrDefault()) & // (tempx.HasValue == tempy.HasValue); // // and x != y as // // tempx = x; // tempy = y; // result = !((tempx.GetValueOrDefault() == tempy.GetValueOrDefault()) & // (tempx.HasValue == tempy.HasValue)); // // Otherwise, we rewrite x OP y as // // tempx = x; // tempy = y; // result = (tempx.GetValueOrDefault() OP tempy.GetValueOrDefault()) & // (tempx.HasValue & tempy.HasValue); // // // Note that there is no reason to generate "&&" over "&"; the cost of // the added code for the conditional branch would be about the same as simply doing // the bitwise & in the first place. // // We have not yet optimized the case where we have a known-not-null value on one side, // and an unknown value on the other. In those cases we will still generate a temp, but // we will not generate the call to the unnecessary nullable ctor or to GetValueOrDefault. // Rather, we will generate the value's temp instead of a call to GetValueOrDefault, and generate // literal true for HasValue. The tree construction methods we call will use those constants // to eliminate unnecessary branches. BoundExpression? xNonNull = NullableAlwaysHasValue(loweredLeft); BoundExpression? yNonNull = NullableAlwaysHasValue(loweredRight); BoundLocal boundTempX = _factory.StoreToTemp(xNonNull ?? loweredLeft, out BoundAssignmentOperator tempAssignmentX); BoundLocal boundTempY = _factory.StoreToTemp(yNonNull ?? loweredRight, out BoundAssignmentOperator tempAssignmentY); BoundExpression callX_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempX); BoundExpression callY_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempY); BoundExpression callX_HasValue = MakeOptimizedHasValue(syntax, boundTempX); BoundExpression callY_HasValue = MakeOptimizedHasValue(syntax, boundTempY); BinaryOperatorKind leftOperator; BinaryOperatorKind rightOperator; BinaryOperatorKind operatorKind = kind.Operator(); switch (operatorKind) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: leftOperator = BinaryOperatorKind.Equal; rightOperator = BinaryOperatorKind.BoolEqual; break; default: leftOperator = operatorKind; rightOperator = BinaryOperatorKind.BoolAnd; break; } TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); // (tempx.GetValueOrDefault() OP tempy.GetValueOrDefault()) BoundExpression leftExpression = MakeBinaryOperator( syntax: syntax, operatorKind: leftOperator.WithType(kind.OperandTypes()), loweredLeft: callX_GetValueOrDefault, loweredRight: callY_GetValueOrDefault, type: boolType, method: null, constrainedToTypeOpt: null); // (tempx.HasValue OP tempy.HasValue) BoundExpression rightExpression = MakeBinaryOperator( syntax: syntax, operatorKind: rightOperator, loweredLeft: callX_HasValue, loweredRight: callY_HasValue, type: boolType, method: null, constrainedToTypeOpt: null); // result = (tempx.GetValueOrDefault() OP tempy.GetValueOrDefault()) & // (tempx.HasValue OP tempy.HasValue) BoundExpression binaryExpression = MakeBinaryOperator( syntax: syntax, operatorKind: BinaryOperatorKind.BoolAnd, loweredLeft: leftExpression, loweredRight: rightExpression, type: boolType, method: null, constrainedToTypeOpt: null); // result = !((tempx.GetValueOrDefault() == tempy.GetValueOrDefault()) & // (tempx.HasValue == tempy.HasValue)); if (operatorKind == BinaryOperatorKind.NotEqual) { binaryExpression = _factory.Not(binaryExpression); } // tempx = x; // tempy = y; // result = (tempx.GetValueOrDefault() == tempy.GetValueOrDefault()) & // (tempx.HasValue == tempy.HasValue); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTempX.LocalSymbol, boundTempY.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignmentX, tempAssignmentY), value: binaryExpression, type: boolType); } private BoundExpression LowerLiftedUserDefinedComparisonOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { // If both sides are null, or neither side is null, then we can do some simple optimizations. BoundExpression? optimized = TrivialLiftedComparisonOperatorOptimizations(syntax, kind, loweredLeft, loweredRight, method, constrainedToTypeOpt); if (optimized != null) { return optimized; } // Otherwise, the expression // // x == y // // becomes // // tempX = x; // tempY = y; // result = tempX.HasValue == tempY.HasValue ? // (tempX.HasValue ? // tempX.GetValueOrDefault() == tempY.GetValueOrDefault() : // true) : // false; // // // the expression // // x != y // // becomes // // tempX = x; // tempY = y; // result = tempX.HasValue == tempY.HasValue ? // (tempX.HasValue ? // tempX.GetValueOrDefault() != tempY.GetValueOrDefault() : // false) : // true; // // // For the other comparison operators <, <=, >, >=, // // x OP y // // becomes // // tempX = x; // tempY = y; // result = tempX.HasValue & tempY.HasValue ? // tempX.GetValueOrDefault() OP tempY.GetValueOrDefault() : // false; // // We have not yet optimized the case where we have a known-not-null value on one side, // and an unknown value on the other. In those cases we will still generate a temp, but // we will not generate the call to the unnecessary nullable ctor or to GetValueOrDefault. // Rather, we will generate the value's temp instead of a call to GetValueOrDefault, and generate // literal true for HasValue. The tree construction methods we call will use those constants // to eliminate unnecessary branches. BoundExpression? xNonNull = NullableAlwaysHasValue(loweredLeft); BoundExpression? yNonNull = NullableAlwaysHasValue(loweredRight); // TODO: (This TODO applies throughout this file, not just to this method.) // TODO: We might be storing a constant to this temporary that we could simply inline. // TODO: (There are other expressions that can be safely moved around other than constants // TODO: as well -- for example a boxing conversion of a constant int to object.) // TODO: Build a better temporary-storage management system that decides whether or not // TODO: to store a temporary. BoundAssignmentOperator tempAssignmentX; BoundLocal boundTempX = _factory.StoreToTemp(xNonNull ?? loweredLeft, out tempAssignmentX); BoundAssignmentOperator tempAssignmentY; BoundLocal boundTempY = _factory.StoreToTemp(yNonNull ?? loweredRight, out tempAssignmentY); BoundExpression callX_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempX); BoundExpression callY_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempY); BoundExpression callX_HasValue = MakeOptimizedHasValue(syntax, boundTempX); BoundExpression callY_HasValue = MakeOptimizedHasValue(syntax, boundTempY); // tempx.HasValue == tempy.HasValue BinaryOperatorKind conditionOperator; BinaryOperatorKind operatorKind = kind.Operator(); switch (operatorKind) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: conditionOperator = BinaryOperatorKind.BoolEqual; break; default: conditionOperator = BinaryOperatorKind.BoolAnd; break; } TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); BoundExpression condition = MakeBinaryOperator( syntax: syntax, operatorKind: conditionOperator, loweredLeft: callX_HasValue, loweredRight: callY_HasValue, type: boolType, method: null, constrainedToTypeOpt: null); // tempX.GetValueOrDefault() OP tempY.GetValueOrDefault() BoundExpression unliftedOp = MakeBinaryOperator( syntax: syntax, operatorKind: kind.Unlifted(), loweredLeft: callX_GetValueOrDefault, loweredRight: callY_GetValueOrDefault, type: boolType, method: method, constrainedToTypeOpt: constrainedToTypeOpt); BoundExpression consequence; if (operatorKind == BinaryOperatorKind.Equal || operatorKind == BinaryOperatorKind.NotEqual) { // tempx.HasValue ? tempX.GetValueOrDefault() == tempY.GetValueOrDefault() : true consequence = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: callX_HasValue, rewrittenConsequence: unliftedOp, rewrittenAlternative: MakeLiteral(syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.Equal), boolType), constantValueOpt: null, rewrittenType: boolType, isRef: false); } else { // tempX.GetValueOrDefault() OP tempY.GetValueOrDefault() consequence = unliftedOp; } // false BoundExpression alternative = MakeBooleanConstant(syntax, operatorKind == BinaryOperatorKind.NotEqual); BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: boolType, isRef: false); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTempX.LocalSymbol, boundTempY.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignmentX, tempAssignmentY), value: conditionalExpression, type: boolType); } private BoundExpression? TrivialLiftedBinaryArithmeticOptimizations( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { // We begin with a trivial optimization: if both operands are null then the // result is known to be null. Debug.Assert(left != null); Debug.Assert(right != null); // Optimization #1: if both sides are null then the result // is either true (for equality) or false (for everything else.) bool leftAlwaysNull = NullableNeverHasValue(left); bool rightAlwaysNull = NullableNeverHasValue(right); if (leftAlwaysNull && rightAlwaysNull) { // default(R?) return new BoundDefaultExpression(syntax, type); } // Optimization #2: If both sides are non-null then we can again eliminate the lifting entirely. BoundExpression? leftNonNull = NullableAlwaysHasValue(left); BoundExpression? rightNonNull = NullableAlwaysHasValue(right); if (leftNonNull != null && rightNonNull != null) { return MakeLiftedBinaryOperatorConsequence(syntax, kind, leftNonNull, rightNonNull, type, method, constrainedToTypeOpt); } return null; } private BoundExpression MakeLiftedBinaryOperatorConsequence( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { // tempX.GetValueOrDefault() OP tempY.GetValueOrDefault() BoundExpression unliftedOp = MakeBinaryOperator( syntax: syntax, operatorKind: kind.Unlifted(), loweredLeft: left, loweredRight: right, type: type.GetNullableUnderlyingType(), method: method, constrainedToTypeOpt: constrainedToTypeOpt); // new R?(tempX.GetValueOrDefault() OP tempY.GetValueOrDefault) return new BoundObjectCreationExpression( syntax, UnsafeGetNullableMethod(syntax, type, SpecialMember.System_Nullable_T__ctor), unliftedOp); } private static BoundExpression? OptimizeLiftedArithmeticOperatorOneNull( SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type) { // Here we optimize the cases where one side is known to be null. If we have // null + M() or null + new int?(M()) then we simply generate M() as a side // effect and produce null. Note that we can optimize away the unnecessary // constructor. bool leftAlwaysNull = NullableNeverHasValue(left); bool rightAlwaysNull = NullableNeverHasValue(right); Debug.Assert(!(leftAlwaysNull && rightAlwaysNull)); // We've already optimized this case. if (!(leftAlwaysNull || rightAlwaysNull)) { return null; } BoundExpression notAlwaysNull = leftAlwaysNull ? right : left; BoundExpression? neverNull = NullableAlwaysHasValue(notAlwaysNull); BoundExpression sideEffect = neverNull ?? notAlwaysNull; // If the "side effect" is a constant then we simply elide it entirely. // TODO: There are expressions other than constants that have no side effects // TODO: or elidable side effects. if (sideEffect.ConstantValue != null) { return new BoundDefaultExpression(syntax, type); } return new BoundSequence( syntax: syntax, locals: ImmutableArray<LocalSymbol>.Empty, sideEffects: ImmutableArray.Create<BoundExpression>(sideEffect), value: new BoundDefaultExpression(syntax, type), type: type); } private BoundExpression LowerLiftedBinaryArithmeticOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { // We have a lifted * / % + - << >> ^ & | binary operator. We begin with trivial // optimizations; if both sides are null or neither side is null then we can // eliminate the lifting altogether. BoundExpression? optimized = OptimizeLiftedBinaryArithmetic(syntax, kind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); if (optimized != null) { return optimized; } // We now know that neither side is null. However, we might have an operand that is known // to be non-null. If neither side is known to be non-null then we generate: // // S? tempX = left; // S? tempY = right; // R? r = tempX.HasValue & tempY.HasValue ? // new R?(tempX.GetValueOrDefault() OP tempY.GetValueOrDefault()) : // default(R?); // // If one of the operands, say the right, is non-null, then we generate: // // S? tempX = left; // S tempY = right; // not null // R? r = tempX.HasValue ? // new R?(tempX.GetValueOrDefault() OP tempY) : // default(R?); // var sideeffects = ArrayBuilder<BoundExpression>.GetInstance(); var locals = ArrayBuilder<LocalSymbol>.GetInstance(); BoundExpression? leftNeverNull = NullableAlwaysHasValue(loweredLeft); BoundExpression? rightNeverNull = NullableAlwaysHasValue(loweredRight); BoundExpression boundTempX = leftNeverNull ?? loweredLeft; boundTempX = CaptureExpressionInTempIfNeeded(boundTempX, sideeffects, locals); BoundExpression boundTempY = rightNeverNull ?? loweredRight; boundTempY = CaptureExpressionInTempIfNeeded(boundTempY, sideeffects, locals); BoundExpression callX_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempX); BoundExpression callY_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempY); BoundExpression callX_HasValue = MakeOptimizedHasValue(syntax, boundTempX); BoundExpression callY_HasValue = MakeOptimizedHasValue(syntax, boundTempY); // tempX.HasValue & tempY.HasValue TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); BoundExpression condition = MakeBinaryOperator(syntax, BinaryOperatorKind.BoolAnd, callX_HasValue, callY_HasValue, boolType, method: null, constrainedToTypeOpt: null); // new R?(tempX.GetValueOrDefault() OP tempY.GetValueOrDefault) BoundExpression consequence = MakeLiftedBinaryOperatorConsequence(syntax, kind, callX_GetValueOrDefault, callY_GetValueOrDefault, type, method, constrainedToTypeOpt); // default(R?) BoundExpression alternative = new BoundDefaultExpression(syntax, type); // tempX.HasValue & tempY.HasValue ? // new R?(tempX.GetValueOrDefault() OP tempY.GetValueOrDefault()) : // default(R?); BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: type, isRef: false); return new BoundSequence( syntax: syntax, locals: locals.ToImmutableAndFree(), sideEffects: sideeffects.ToImmutableAndFree(), value: conditionalExpression, type: type); } private BoundExpression CaptureExpressionInTempIfNeeded( BoundExpression operand, ArrayBuilder<BoundExpression> sideeffects, ArrayBuilder<LocalSymbol> locals, SynthesizedLocalKind kind = SynthesizedLocalKind.LoweringTemp) { if (CanChangeValueBetweenReads(operand)) { BoundAssignmentOperator tempAssignment; var tempAccess = _factory.StoreToTemp(operand, out tempAssignment, kind: kind); sideeffects.Add(tempAssignment); locals.Add(tempAccess.LocalSymbol); operand = tempAccess; } return operand; } private BoundExpression? OptimizeLiftedBinaryArithmetic( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { BoundExpression? optimized = TrivialLiftedBinaryArithmeticOptimizations(syntax, kind, left, right, type, method, constrainedToTypeOpt); if (optimized != null) { return optimized; } // Boolean & and | operators have completely different codegen in non-trivial cases. if (kind == BinaryOperatorKind.LiftedBoolAnd || kind == BinaryOperatorKind.LiftedBoolOr) { return LowerLiftedBooleanOperator(syntax, kind, left, right); } // If one side is null then we can lower this to a side effect and a null value. optimized = OptimizeLiftedArithmeticOperatorOneNull(syntax, left, right, type); if (optimized != null) { return optimized; } // This is a bit of a complicated optimization; it is a more complex version of the // "distributed" optimizations for lifted conversions and lifted unary operators. // // Suppose we have a lifted binary operation where the left side might be null or not, // and the right side is definitely not, and moreover, it is a constant. We are particularly // concerned about this because expressions like "i++" and "i += 1" are lowered to "i = i + 1"; // it is quite common for there to be a constant on the left hand side of a lifted binop. // // Here N() returns int?: // // return N() + 1; // // In LowerLiftedBinaryOperator, above, we would optimize this as: // // int? n = N(); // int v = 1; // return n.HasValue ? new int?(n.Value + v) : new int?() // // This is unfortunate in that we generate an unnecessary temporary, but that's // not what we're going to optimize away here. This codegen is pretty good. // // Now let's suppose that instead of N(), we have a lifted operation on the left side: // // return (N1() * N2()) + 1; // // We could realize the left hand term as a lifted multiplication, produce a nullable int, // assign it to a temporary, and do the lifted addition: // // int? n1 = N1(); // int? n2 = N2(); // int? r = n1.HasValue & n2.HasValue ? new int?(n1.Value * n2.Value) : new int?(); // int v = 1; // return r.HasValue ? new int?(r.Value + v) : new int?(); // // But what is the point of the temporary r in this expansion? We can eliminate it, and // thereby eliminate two int? constructors in the process. We can realize this as: // // int? n1 = N1(); // int? n2 = N2(); // return n1.HasValue & n2.HasValue ? new int?(n1.Value * n2.Value + 1) : new int?(); // // We eliminate both the temporaries r and v. // // Now, a reasonable question at this point would be "well, suppose the expression on // the right side is not a constant, but is known to be non-null; can we do the same // optimization?" No, and here's why. Suppose we have: // // return (N1() * N2()) + V(); // // We cannot realize this as: // // int? n1 = N1(); // int? n2 = N2(); // int v = V(); // return n1.HasValue & n2.HasValue ? new int?(n1.Value * n2.Value + v) : new int?(); // // because this changes the order in which the operations happen. Before we had N1(), // N2(), the multiplication -- which might be a user-defined operator with a side effect, // or might be in a checked context and overflow -- and then V(). Now we have V() before // the multiplication, changing the order in which side effects occur. // // We could solve this problem by generating: // // int? n1 = N1(); // int? n2 = N2(); // return n1.HasValue & n2.HasValue ? new int?(n1.Value * n2.Value + V()) : (V(), new int?()); // so that the side effects of V() happen after the multiplication or before the value is // produced, but now we have generated IL for V() twice. That could be a complex expression // and the whole point of this optimization is to make less IL. // // We could, however, optimize it if the non-null V() was on the left hand side. At this // time we will not pursue that optimization. We're really just hoping to get the N1() * N2() + 1 // operation smaller; the rest is gravy. BoundExpression? nonNullRight = NullableAlwaysHasValue(right); if (nonNullRight != null && nonNullRight.ConstantValue != null && left.Kind == BoundKind.Sequence) { BoundSequence seq = (BoundSequence)left; if (seq.Value.Kind == BoundKind.ConditionalOperator) { BoundConditionalOperator conditional = (BoundConditionalOperator)seq.Value; Debug.Assert(TypeSymbol.Equals(seq.Type, conditional.Type, TypeCompareKind.ConsiderEverything2)); Debug.Assert(TypeSymbol.Equals(conditional.Type, conditional.Consequence.Type, TypeCompareKind.ConsiderEverything2)); Debug.Assert(TypeSymbol.Equals(conditional.Type, conditional.Alternative.Type, TypeCompareKind.ConsiderEverything2)); if (NullableAlwaysHasValue(conditional.Consequence) != null && NullableNeverHasValue(conditional.Alternative)) { return new BoundSequence( syntax, seq.Locals, seq.SideEffects, RewriteConditionalOperator( syntax, conditional.Condition, MakeBinaryOperator(syntax, kind, conditional.Consequence, right, type, method, constrainedToTypeOpt), MakeBinaryOperator(syntax, kind, conditional.Alternative, right, type, method, constrainedToTypeOpt), ConstantValue.NotAvailable, type, isRef: false), type); } } } return null; } private BoundExpression MakeNewNullableBoolean(SyntaxNode syntax, bool? value) { NamedTypeSymbol nullableType = _compilation.GetSpecialType(SpecialType.System_Nullable_T); TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); NamedTypeSymbol nullableBoolType = nullableType.Construct(boolType); if (value == null) { return new BoundDefaultExpression(syntax, nullableBoolType); } return new BoundObjectCreationExpression( syntax, UnsafeGetNullableMethod(syntax, nullableBoolType, SpecialMember.System_Nullable_T__ctor), MakeBooleanConstant(syntax, value.GetValueOrDefault())); } private BoundExpression? OptimizeLiftedBooleanOperatorOneNull( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { // Here we optimize the cases where one side is known to be null. bool leftAlwaysNull = NullableNeverHasValue(left); bool rightAlwaysNull = NullableNeverHasValue(right); Debug.Assert(!(leftAlwaysNull && rightAlwaysNull)); // We've already optimized this case. if (!(leftAlwaysNull || rightAlwaysNull)) { return null; } // First, if one operand is null and the other is definitely non null, then we can eliminate // all the temporaries: // // new bool?() & new bool?(B()) // new bool?() | new bool?(B()) // // can be generated as // // B() ? new bool?() : new bool?(false) // B() ? new bool?(true) : new bool?() // // respectively. BoundExpression alwaysNull = leftAlwaysNull ? left : right; BoundExpression notAlwaysNull = leftAlwaysNull ? right : left; BoundExpression? neverNull = NullableAlwaysHasValue(notAlwaysNull); Debug.Assert(alwaysNull.Type is { }); BoundExpression nullBool = new BoundDefaultExpression(syntax, alwaysNull.Type); if (neverNull != null) { BoundExpression newNullBool = MakeNewNullableBoolean(syntax, kind == BinaryOperatorKind.LiftedBoolOr); return RewriteConditionalOperator( syntax: syntax, rewrittenCondition: neverNull, rewrittenConsequence: kind == BinaryOperatorKind.LiftedBoolAnd ? nullBool : newNullBool, rewrittenAlternative: kind == BinaryOperatorKind.LiftedBoolAnd ? newNullBool : nullBool, constantValueOpt: null, rewrittenType: alwaysNull.Type, isRef: false); } // Now we optimize the case where one operand is null and the other is not. We generate // // new bool?() & M() // new bool?() | M() // // as // // bool? t = M(), t.GetValueOrDefault() ? new bool?() : t // bool? t = M(), t.GetValueOrDefault() ? t : new bool?() // // respectively. BoundAssignmentOperator tempAssignment; BoundLocal boundTemp = _factory.StoreToTemp(notAlwaysNull, out tempAssignment); BoundExpression condition = MakeOptimizedGetValueOrDefault(syntax, boundTemp); BoundExpression consequence = kind == BinaryOperatorKind.LiftedBoolAnd ? nullBool : boundTemp; BoundExpression alternative = kind == BinaryOperatorKind.LiftedBoolAnd ? boundTemp : nullBool; BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: alwaysNull.Type, isRef: false); Debug.Assert(conditionalExpression.Type is { }); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTemp.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment), value: conditionalExpression, type: conditionalExpression.Type); } private BoundExpression? OptimizeLiftedBooleanOperatorOneNonNull( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { // Here we optimize the cases where one side is known to be non-null. We generate: // // new bool?(B()) & N() // N() & new bool?(B()) // new bool?(B()) | N() // N() | new bool?(B()) // // as // // bool b = B(), bool? n = N(), b ? n : new bool?(false) // bool? n = N(), bool b = B(), b ? n : new bool?(false) // bool b = B(), bool? n = N(), b ? new bool?(true) : n // bool? n = N(), bool b = B(), b ? new bool?(true) : n // // respectively. BoundExpression? leftNonNull = NullableAlwaysHasValue(left); BoundExpression? rightNonNull = NullableAlwaysHasValue(right); Debug.Assert(leftNonNull == null || rightNonNull == null); // We've already optimized the case where they are both non-null. Debug.Assert(!NullableNeverHasValue(left) && !NullableNeverHasValue(right)); // We've already optimized the case where one is null. if (leftNonNull == null && rightNonNull == null) { return null; } // One is definitely not null and the other might be null. BoundAssignmentOperator tempAssignmentX; BoundLocal boundTempX = _factory.StoreToTemp(leftNonNull ?? left, out tempAssignmentX); BoundAssignmentOperator tempAssignmentY; BoundLocal boundTempY = _factory.StoreToTemp(rightNonNull ?? right, out tempAssignmentY); BoundExpression nonNullTemp = leftNonNull == null ? boundTempY : boundTempX; BoundExpression maybeNullTemp = leftNonNull == null ? boundTempX : boundTempY; BoundExpression condition = nonNullTemp; BoundExpression newNullBool = MakeNewNullableBoolean(syntax, kind == BinaryOperatorKind.LiftedBoolOr); BoundExpression consequence = kind == BinaryOperatorKind.LiftedBoolOr ? newNullBool : maybeNullTemp; BoundExpression alternative = kind == BinaryOperatorKind.LiftedBoolOr ? maybeNullTemp : newNullBool; BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: newNullBool.Type!, isRef: false); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTempX.LocalSymbol, boundTempY.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignmentX, tempAssignmentY), value: conditionalExpression, type: conditionalExpression.Type!); } private BoundExpression LowerLiftedBooleanOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight) { // x & y and x | y have special codegen if x and y are nullable Booleans. // We have already optimized cases where both operands are null or both are non-null. // Now optimize cases where one side is known to be null or one side is known to be non-null. BoundExpression? optimized = OptimizeLiftedBooleanOperatorOneNull(syntax, kind, loweredLeft, loweredRight); if (optimized != null) { return optimized; } optimized = OptimizeLiftedBooleanOperatorOneNonNull(syntax, kind, loweredLeft, loweredRight); if (optimized != null) { return optimized; } // x & y is realized as (x.GetValueOrDefault() || !(y.GetValueOrDefault() || x.HasValue)) ? y : x // x | y is realized as (x.GetValueOrDefault() || !(y.GetValueOrDefault() || x.HasValue)) ? x : y // CONSIDER: Consider realizing these using | instead of ||. // CONSIDER: The operations are extremely low cost and the added bulk to the code might not be worthwhile. BoundAssignmentOperator tempAssignmentX; BoundLocal boundTempX = _factory.StoreToTemp(loweredLeft, out tempAssignmentX); BoundAssignmentOperator tempAssignmentY; BoundLocal boundTempY = _factory.StoreToTemp(loweredRight, out tempAssignmentY); TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); MethodSymbol getValueOrDefaultX = UnsafeGetNullableMethod(syntax, boundTempX.Type, SpecialMember.System_Nullable_T_GetValueOrDefault); MethodSymbol getValueOrDefaultY = UnsafeGetNullableMethod(syntax, boundTempY.Type, SpecialMember.System_Nullable_T_GetValueOrDefault); // tempx.GetValueOrDefault() BoundExpression callX_GetValueOrDefault = BoundCall.Synthesized(syntax, boundTempX, getValueOrDefaultX); // tempy.GetValueOrDefault() BoundExpression callY_GetValueOrDefault = BoundCall.Synthesized(syntax, boundTempY, getValueOrDefaultY); // tempx.HasValue BoundExpression callX_HasValue = MakeNullableHasValue(syntax, boundTempX); // (tempy.GetValueOrDefault || tempx.HasValue) BoundExpression innerOr = MakeBinaryOperator( syntax: syntax, operatorKind: BinaryOperatorKind.LogicalBoolOr, loweredLeft: callY_GetValueOrDefault, loweredRight: callX_HasValue, type: boolType, method: null, constrainedToTypeOpt: null); // !(tempy.GetValueOrDefault || tempx.HasValue) BoundExpression invert = MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, innerOr, boolType); // (x.GetValueOrDefault() || !(y.GetValueOrDefault() || x.HasValue)) BoundExpression condition = MakeBinaryOperator( syntax: syntax, operatorKind: BinaryOperatorKind.LogicalBoolOr, loweredLeft: callX_GetValueOrDefault, loweredRight: invert, type: boolType, method: null, constrainedToTypeOpt: null); BoundExpression consequence = kind == BinaryOperatorKind.LiftedBoolAnd ? boundTempY : boundTempX; BoundExpression alternative = kind == BinaryOperatorKind.LiftedBoolAnd ? boundTempX : boundTempY; BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: alternative.Type!, isRef: false); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTempX.LocalSymbol, boundTempY.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignmentX, tempAssignmentY), value: conditionalExpression, type: conditionalExpression.Type!); } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetNullableMethod"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private MethodSymbol UnsafeGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member) { return UnsafeGetNullableMethod(syntax, nullableType, member, _compilation, _diagnostics); } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetNullableMethod"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private static MethodSymbol UnsafeGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { var nullableType2 = nullableType as NamedTypeSymbol; Debug.Assert(nullableType2 is { }); return UnsafeGetSpecialTypeMethod(syntax, member, compilation, diagnostics).AsMember(nullableType2); } private bool TryGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member, out MethodSymbol result) { var nullableType2 = (NamedTypeSymbol)nullableType; if (TryGetSpecialTypeMethod(syntax, member, out result)) { result = result.AsMember(nullableType2); return true; } return false; } private BoundExpression RewriteNullableNullEquality( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType) { // This handles the case where we have a nullable user-defined struct type compared against null, eg: // // struct S {} ... S? s = whatever; if (s != null) // // If S does not define an overloaded != operator then this is lowered to s.HasValue. // // If the type already has a user-defined or built-in operator then comparing to null is // treated as a lifted equality operator. Debug.Assert(loweredLeft != null); Debug.Assert(loweredRight != null); Debug.Assert((object)returnType != null); Debug.Assert(returnType.SpecialType == SpecialType.System_Boolean); Debug.Assert(loweredLeft.IsLiteralNull() != loweredRight.IsLiteralNull()); BoundExpression nullable = loweredRight.IsLiteralNull() ? loweredLeft : loweredRight; // If the other side is known to always be null then we can simply generate true or false, as appropriate. if (NullableNeverHasValue(nullable)) { return MakeLiteral(syntax, ConstantValue.Create(kind == BinaryOperatorKind.NullableNullEqual), returnType); } BoundExpression? nonNullValue = NullableAlwaysHasValue(nullable); if (nonNullValue != null) { // We have something like "if (new int?(M()) != null)". We can optimize this to // evaluate M() for its side effects and then result in true or false, as appropriate. // TODO: If the expression has no side effects then it can be optimized away here as well. return new BoundSequence( syntax: syntax, locals: ImmutableArray<LocalSymbol>.Empty, sideEffects: ImmutableArray.Create<BoundExpression>(nonNullValue), value: MakeBooleanConstant(syntax, kind == BinaryOperatorKind.NullableNullNotEqual), type: returnType); } // arr?.Length == null var conditionalAccess = nullable as BoundLoweredConditionalAccess; if (conditionalAccess != null && (conditionalAccess.WhenNullOpt == null || conditionalAccess.WhenNullOpt.IsDefaultValue())) { BoundExpression whenNotNull = RewriteNullableNullEquality( syntax, kind, conditionalAccess.WhenNotNull, loweredLeft.IsLiteralNull() ? loweredLeft : loweredRight, returnType); var whenNull = kind == BinaryOperatorKind.NullableNullEqual ? MakeBooleanConstant(syntax, true) : null; return conditionalAccess.Update(conditionalAccess.Receiver, conditionalAccess.HasValueMethodOpt, whenNotNull, whenNull, conditionalAccess.Id, whenNotNull.Type!); } BoundExpression call = MakeNullableHasValue(syntax, nullable); BoundExpression result = kind == BinaryOperatorKind.NullableNullNotEqual ? call : new BoundUnaryOperator(syntax, UnaryOperatorKind.BoolLogicalNegation, call, ConstantValue.NotAvailable, null, constrainedToTypeOpt: null, LookupResultKind.Viable, returnType); return result; } private BoundExpression RewriteStringEquality(BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, SpecialMember member) { if (oldNode != null && (loweredLeft.ConstantValue == ConstantValue.Null || loweredRight.ConstantValue == ConstantValue.Null)) { return oldNode.Update(operatorKind, oldNode.ConstantValue, oldNode.Method, oldNode.ConstrainedToType, oldNode.ResultKind, loweredLeft, loweredRight, type); } var method = UnsafeGetSpecialTypeMethod(syntax, member); Debug.Assert((object)method != null); return BoundCall.Synthesized(syntax, receiverOpt: null, method, loweredLeft, loweredRight); } private BoundExpression RewriteDelegateOperation(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, SpecialMember member) { MethodSymbol method; if (operatorKind == BinaryOperatorKind.DelegateEqual || operatorKind == BinaryOperatorKind.DelegateNotEqual) { method = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member); if (loweredRight.IsLiteralNull() || loweredLeft.IsLiteralNull() || (object)(method = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member)) == null) { // use reference equality in the absence of overloaded operators for System.Delegate. operatorKind = (operatorKind & (~BinaryOperatorKind.Delegate)) | BinaryOperatorKind.Object; return new BoundBinaryOperator(syntax, operatorKind, constantValueOpt: null, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Empty, loweredLeft, loweredRight, type); } } else { method = UnsafeGetSpecialTypeMethod(syntax, member); } Debug.Assert((object)method != null); BoundExpression call = _inExpressionLambda ? new BoundBinaryOperator(syntax, operatorKind, null, method, constrainedToTypeOpt: null, default(LookupResultKind), loweredLeft, loweredRight, method.ReturnType) : (BoundExpression)BoundCall.Synthesized(syntax, receiverOpt: null, method, loweredLeft, loweredRight); BoundExpression result = method.ReturnType.SpecialType == SpecialType.System_Delegate ? MakeConversionNode(syntax, call, Conversion.ExplicitReference, type, @checked: false) : call; return result; } private BoundExpression RewriteDecimalBinaryOperation(SyntaxNode syntax, BoundExpression loweredLeft, BoundExpression loweredRight, BinaryOperatorKind operatorKind) { Debug.Assert(loweredLeft.Type is { SpecialType: SpecialType.System_Decimal }); Debug.Assert(loweredRight.Type is { SpecialType: SpecialType.System_Decimal }); SpecialMember member; switch (operatorKind) { case BinaryOperatorKind.DecimalAddition: member = SpecialMember.System_Decimal__op_Addition; break; case BinaryOperatorKind.DecimalSubtraction: member = SpecialMember.System_Decimal__op_Subtraction; break; case BinaryOperatorKind.DecimalMultiplication: member = SpecialMember.System_Decimal__op_Multiply; break; case BinaryOperatorKind.DecimalDivision: member = SpecialMember.System_Decimal__op_Division; break; case BinaryOperatorKind.DecimalRemainder: member = SpecialMember.System_Decimal__op_Modulus; break; case BinaryOperatorKind.DecimalEqual: member = SpecialMember.System_Decimal__op_Equality; break; case BinaryOperatorKind.DecimalNotEqual: member = SpecialMember.System_Decimal__op_Inequality; break; case BinaryOperatorKind.DecimalLessThan: member = SpecialMember.System_Decimal__op_LessThan; break; case BinaryOperatorKind.DecimalLessThanOrEqual: member = SpecialMember.System_Decimal__op_LessThanOrEqual; break; case BinaryOperatorKind.DecimalGreaterThan: member = SpecialMember.System_Decimal__op_GreaterThan; break; case BinaryOperatorKind.DecimalGreaterThanOrEqual: member = SpecialMember.System_Decimal__op_GreaterThanOrEqual; break; default: throw ExceptionUtilities.UnexpectedValue(operatorKind); } // call Operator (left, right) var method = UnsafeGetSpecialTypeMethod(syntax, member); Debug.Assert((object)method != null); return BoundCall.Synthesized(syntax, receiverOpt: null, method, loweredLeft, loweredRight); } private BoundExpression MakeNullCheck(SyntaxNode syntax, BoundExpression rewrittenExpr, BinaryOperatorKind operatorKind) { Debug.Assert((operatorKind == BinaryOperatorKind.Equal) || (operatorKind == BinaryOperatorKind.NotEqual) || (operatorKind == BinaryOperatorKind.NullableNullEqual) || (operatorKind == BinaryOperatorKind.NullableNullNotEqual)); TypeSymbol? exprType = rewrittenExpr.Type; // Don't even call this method if the expression cannot be nullable. Debug.Assert( exprType is null || exprType.IsNullableTypeOrTypeParameter() || !exprType.IsValueType || exprType.IsPointerOrFunctionPointer()); TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); // Fold compile-time comparisons. if (rewrittenExpr.ConstantValue != null) { switch (operatorKind) { case BinaryOperatorKind.Equal: return MakeLiteral(syntax, ConstantValue.Create(rewrittenExpr.ConstantValue.IsNull, ConstantValueTypeDiscriminator.Boolean), boolType); case BinaryOperatorKind.NotEqual: return MakeLiteral(syntax, ConstantValue.Create(!rewrittenExpr.ConstantValue.IsNull, ConstantValueTypeDiscriminator.Boolean), boolType); } } TypeSymbol objectType = _compilation.GetSpecialType(SpecialType.System_Object); if (exprType is { }) { if (exprType.Kind == SymbolKind.TypeParameter) { // Box type parameters. rewrittenExpr = MakeConversionNode(syntax, rewrittenExpr, Conversion.Boxing, objectType, @checked: false); } else if (exprType.IsNullableType()) { operatorKind |= BinaryOperatorKind.NullableNull; } } return MakeBinaryOperator( syntax, operatorKind, rewrittenExpr, MakeLiteral(syntax, ConstantValue.Null, objectType), boolType, method: null, constrainedToTypeOpt: null); } /// <summary> /// Spec section 7.9: if the left operand is int or uint, mask the right operand with 0x1F; /// if the left operand is long or ulong, mask the right operand with 0x3F. /// </summary> private BoundExpression RewriteBuiltInShiftOperation( BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, int rightMask) { SyntaxNode rightSyntax = loweredRight.Syntax; ConstantValue? rightConstantValue = loweredRight.ConstantValue; Debug.Assert(loweredRight.Type is { }); TypeSymbol rightType = loweredRight.Type; Debug.Assert(rightType.SpecialType == SpecialType.System_Int32); if (rightConstantValue != null && rightConstantValue.IsIntegral) { int shiftAmount = rightConstantValue.Int32Value & rightMask; if (shiftAmount == 0) { return loweredLeft; } loweredRight = MakeLiteral(rightSyntax, ConstantValue.Create(shiftAmount), rightType); } else { BinaryOperatorKind andOperatorKind = (operatorKind & ~BinaryOperatorKind.OpMask) | BinaryOperatorKind.And; loweredRight = new BoundBinaryOperator( rightSyntax, andOperatorKind, null, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, loweredRight, MakeLiteral(rightSyntax, ConstantValue.Create(rightMask), rightType), rightType); } return oldNode == null ? new BoundBinaryOperator( syntax, operatorKind, null, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, loweredLeft, loweredRight, type) : oldNode.Update( operatorKind, null, methodOpt: null, constrainedToTypeOpt: null, oldNode.ResultKind, loweredLeft, loweredRight, type); } private BoundExpression RewritePointerNumericOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType, bool isPointerElementAccess, bool isLeftPointer) { if (isLeftPointer) { Debug.Assert(loweredLeft.Type is { TypeKind: TypeKind.Pointer }); loweredRight = MakeSizeOfMultiplication(loweredRight, (PointerTypeSymbol)loweredLeft.Type, kind.IsChecked()); } else { Debug.Assert(loweredRight.Type is { TypeKind: TypeKind.Pointer }); loweredLeft = MakeSizeOfMultiplication(loweredLeft, (PointerTypeSymbol)loweredRight.Type, kind.IsChecked()); } if (isPointerElementAccess) { Debug.Assert(kind.Operator() == BinaryOperatorKind.Addition); // NOTE: This is here to persist a bug in Dev10. checked(p[n]) should be equivalent to checked(*(p + n)), // but Dev10 omits the check on the addition (though it retains the check on the multiplication of n by // the size). kind = kind & ~BinaryOperatorKind.Checked; } return new BoundBinaryOperator( syntax, kind, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, loweredLeft, loweredRight, returnType); } /// <summary> /// This rather confusing method tries to reproduce the functionality of ExpressionBinder::bindPtrAddMul and /// ExpressionBinder::bindPtrMul. The basic idea is that we have a numeric expression, x, and a pointer type, /// T*, and we want to multiply x by sizeof(T). Unfortunately, we need to stick in some conversions to make /// everything work. /// /// 1) If x is an int, then convert it to an IntPtr (i.e. a native int). Dev10 offers no explanation (ExpressionBinder::bindPtrMul). /// 2) Do overload resolution based on the (possibly converted) type of X and int (the type of sizeof(T)). /// 3) If the result type of the chosen multiplication operator is signed, convert the product to IntPtr; /// otherwise, convert the product to UIntPtr. /// </summary> private BoundExpression MakeSizeOfMultiplication(BoundExpression numericOperand, PointerTypeSymbol pointerType, bool isChecked) { var sizeOfExpression = _factory.Sizeof(pointerType.PointedAtType); Debug.Assert(sizeOfExpression.Type is { SpecialType: SpecialType.System_Int32 }); // Common case: adding or subtracting one (e.g. for ++) if (numericOperand.ConstantValue?.UInt64Value == 1) { // We could convert this to a native int (as the unoptimized multiplication would be), // but that would be a no-op (int to native int), so don't bother. return sizeOfExpression; } Debug.Assert(numericOperand.Type is { }); var numericSpecialType = numericOperand.Type.SpecialType; // Optimization: the size is exactly one byte, then multiplication is unnecessary. if (sizeOfExpression.ConstantValue?.Int32Value == 1) { // As in ExpressionBinder::bindPtrAddMul, we apply the following conversions: // int -> int (add allows int32 operands and will extend to native int if necessary) // uint -> native uint (add will sign-extend 32bit operand on 64bit, we do not want that happening) // long -> native int // ulong -> native uint // Note that these are not the types we would see if we let the multiplication happen. // ACASEY: These rules are inferred from the native compiler. SpecialType destinationType = numericSpecialType; switch (numericSpecialType) { case SpecialType.System_Int32: // add operator can take int32 and extend to 64bit if necessary // however in a case of checked operation, the operation is treated as unsigned with overflow ( add.ovf.un , sub.ovf.un ) // the IL spec is a bit vague whether JIT should sign or zero extend the shorter operand in such case // and there could be inconsistencies in implementation or bugs. // As a result, in checked contexts, we will force sign-extending cast to be sure if (isChecked) { var constVal = numericOperand.ConstantValue; if (constVal == null || constVal.Int32Value < 0) { destinationType = SpecialType.System_IntPtr; } } break; case SpecialType.System_UInt32: { // add operator treats operands as signed and will sign-extend on x64 // to prevent sign-extending, convert the operand to unsigned native int. var constVal = numericOperand.ConstantValue; if (constVal == null || constVal.UInt32Value > int.MaxValue) { destinationType = SpecialType.System_UIntPtr; } } break; case SpecialType.System_Int64: destinationType = SpecialType.System_IntPtr; break; case SpecialType.System_UInt64: destinationType = SpecialType.System_UIntPtr; break; default: throw ExceptionUtilities.UnexpectedValue(numericSpecialType); } return destinationType == numericSpecialType ? numericOperand : _factory.Convert(_factory.SpecialType(destinationType), numericOperand, Conversion.IntegerToPointer); } BinaryOperatorKind multiplicationKind = BinaryOperatorKind.Multiplication; TypeSymbol multiplicationResultType; TypeSymbol convertedMultiplicationResultType; switch (numericSpecialType) { case SpecialType.System_Int32: { TypeSymbol nativeIntType = _factory.SpecialType(SpecialType.System_IntPtr); // From ExpressionBinder::bindPtrMul: // this multiplication needs to be done as natural ints, but since a (int * natint) ==> natint, // we only need to promote one side numericOperand = _factory.Convert(nativeIntType, numericOperand, Conversion.IntegerToPointer, isChecked); multiplicationKind |= BinaryOperatorKind.Int; //i.e. signed multiplicationResultType = nativeIntType; convertedMultiplicationResultType = nativeIntType; break; } case SpecialType.System_UInt32: { TypeSymbol longType = _factory.SpecialType(SpecialType.System_Int64); TypeSymbol nativeIntType = _factory.SpecialType(SpecialType.System_IntPtr); // We're multiplying a uint by an int, so promote both to long (same as normal operator overload resolution). numericOperand = _factory.Convert(longType, numericOperand, Conversion.ExplicitNumeric, isChecked); sizeOfExpression = _factory.Convert(longType, sizeOfExpression, Conversion.ExplicitNumeric, isChecked); multiplicationKind |= BinaryOperatorKind.Long; multiplicationResultType = longType; convertedMultiplicationResultType = nativeIntType; break; } case SpecialType.System_Int64: { TypeSymbol longType = _factory.SpecialType(SpecialType.System_Int64); TypeSymbol nativeIntType = _factory.SpecialType(SpecialType.System_IntPtr); // We're multiplying a long by an int, so promote the int to long (same as normal operator overload resolution). sizeOfExpression = _factory.Convert(longType, sizeOfExpression, Conversion.ExplicitNumeric, isChecked); multiplicationKind |= BinaryOperatorKind.Long; multiplicationResultType = longType; convertedMultiplicationResultType = nativeIntType; break; } case SpecialType.System_UInt64: { TypeSymbol ulongType = _factory.SpecialType(SpecialType.System_UInt64); TypeSymbol nativeUIntType = _factory.SpecialType(SpecialType.System_UIntPtr); // We're multiplying a ulong by an int, so promote the int to ulong (same as normal operator overload resolution). sizeOfExpression = _factory.Convert(ulongType, sizeOfExpression, Conversion.ExplicitNumeric, isChecked); multiplicationKind |= BinaryOperatorKind.ULong; multiplicationResultType = ulongType; convertedMultiplicationResultType = nativeUIntType; //unsigned since multiplicationResultType is unsigned break; } default: { throw ExceptionUtilities.UnexpectedValue(numericSpecialType); } } if (isChecked) { multiplicationKind |= BinaryOperatorKind.Checked; } var multiplication = _factory.Binary(multiplicationKind, multiplicationResultType, numericOperand, sizeOfExpression); return TypeSymbol.Equals(convertedMultiplicationResultType, multiplicationResultType, TypeCompareKind.ConsiderEverything2) ? multiplication : _factory.Convert(convertedMultiplicationResultType, multiplication, Conversion.IntegerToPointer); // NOTE: for some reason, dev10 doesn't check this conversion. } private BoundExpression RewritePointerSubtraction( BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType) { Debug.Assert(loweredLeft.Type is { TypeKind: TypeKind.Pointer }); Debug.Assert(loweredRight.Type is { TypeKind: TypeKind.Pointer }); Debug.Assert(returnType.SpecialType == SpecialType.System_Int64); PointerTypeSymbol pointerType = (PointerTypeSymbol)loweredLeft.Type; var sizeOfExpression = _factory.Sizeof(pointerType.PointedAtType); // NOTE: to match dev10, the result of the subtraction is treated as an IntPtr // and then the result of the division is converted to long. // NOTE: dev10 doesn't optimize away division by 1. return _factory.Convert( returnType, _factory.Binary( BinaryOperatorKind.Division, _factory.SpecialType(SpecialType.System_IntPtr), _factory.Binary( kind & ~BinaryOperatorKind.Checked, // For some reason, dev10 never checks for subtraction overflow. returnType, loweredLeft, loweredRight), sizeOfExpression), Conversion.PointerToInteger); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { return VisitBinaryOperator(node, null); } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { // Yes, we could have a lifted, logical, user-defined operator: // // struct C { // public static C operator &(C x, C y) {...} // public static bool operator true(C? c) { ... } // public static bool operator false(C? c) { ... } // } // // If we have C? q, r and we say q && r then this gets bound as // C? tempQ = q ; // C.false(tempQ) ? // tempQ : // ( // C? tempR = r ; // tempQ.HasValue & tempR.HasValue ? // new C?(C.&(tempQ.GetValueOrDefault(), tempR.GetValueOrDefault())) : // default C?() // ) // // Note that the native compiler does not allow q && r. However, the native compiler // *does* allow q && r if C is defined as: // // struct C { // public static C? operator &(C? x, C? y) {...} // public static bool operator true(C? c) { ... } // public static bool operator false(C? c) { ... } // } // // It seems unusual and wrong that an & operator should be allowed to become // a && operator if there is a "manually lifted" operator in source, but not // if there is a "synthesized" lifted operator. Roslyn fixes this bug. // // Anyway, in this case we must lower this to its non-logical form, and then // lower the interior of that to its non-lifted form. // See comments in method IsValidUserDefinedConditionalLogicalOperator for information // on some subtle aspects of this lowering. // We generate one of: // // x || y --> temp = x; T.true(temp) ? temp : T.|(temp, y); // x && y --> temp = x; T.false(temp) ? temp : T.&(temp, y); // // For the ease of naming locals, we'll assume we're doing an &&. // TODO: We generate every one of these as "temp = x; T.false(temp) ? temp : T.&(temp, y)" even // TODO: when x has no side effects. We can optimize away the temporary if there are no side effects. var syntax = node.Syntax; var operatorKind = node.OperatorKind; var type = node.Type; BoundExpression loweredLeft = VisitExpression(node.Left); BoundExpression loweredRight = VisitExpression(node.Right); if (_inExpressionLambda) { return node.Update(operatorKind, node.LogicalOperator, node.TrueOperator, node.FalseOperator, node.ConstrainedToTypeOpt, node.ResultKind, loweredLeft, loweredRight, type); } BoundAssignmentOperator tempAssignment; var boundTemp = _factory.StoreToTemp(loweredLeft, out tempAssignment); // T.false(temp) var falseOperatorCall = BoundCall.Synthesized(syntax, receiverOpt: node.ConstrainedToTypeOpt is null ? null : new BoundTypeExpression(syntax, aliasOpt: null, node.ConstrainedToTypeOpt), operatorKind.Operator() == BinaryOperatorKind.And ? node.FalseOperator : node.TrueOperator, boundTemp); // T.&(temp, y) var andOperatorCall = LowerUserDefinedBinaryOperator(syntax, operatorKind & ~BinaryOperatorKind.Logical, boundTemp, loweredRight, type, node.LogicalOperator, node.ConstrainedToTypeOpt); // T.false(temp) ? temp : T.&(temp, y) BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: falseOperatorCall, rewrittenConsequence: boundTemp, rewrittenAlternative: andOperatorCall, constantValueOpt: null, rewrittenType: type, isRef: false); // temp = x; T.false(temp) ? temp : T.&(temp, y) return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create(boundTemp.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment), value: conditionalExpression, type: type); } public BoundExpression VisitBinaryOperator(BoundBinaryOperator node, BoundUnaryOperator? applyParentUnaryOperator) { if (node.InterpolatedStringHandlerData is InterpolatedStringHandlerData data) { Debug.Assert(node.Type.SpecialType == SpecialType.System_String, "Non-string binary addition should have been handled by VisitConversion or VisitArguments"); ImmutableArray<BoundExpression> parts = CollectBinaryOperatorInterpolatedStringParts(node); return LowerPartsToString(data, parts, node.Syntax, node.Type); } // In machine-generated code we frequently end up with binary operator trees that are deep on the left, // such as a + b + c + d ... // To avoid blowing the call stack, we make an explicit stack of the binary operators to the left, // and then lower by traversing the explicit stack. var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); for (BoundBinaryOperator? current = node; current != null && current.ConstantValue == null; current = current.Left as BoundBinaryOperator) { // The regular visit mechanism will handle this. if (current.InterpolatedStringHandlerData is not null) { Debug.Assert(stack.Count >= 1); break; } stack.Push(current); } BoundExpression loweredLeft = VisitExpression(stack.Peek().Left); while (stack.Count > 0) { BoundBinaryOperator original = stack.Pop(); BoundExpression loweredRight = VisitExpression(original.Right); loweredLeft = MakeBinaryOperator(original, original.Syntax, original.OperatorKind, loweredLeft, loweredRight, original.Type, original.Method, original.ConstrainedToType, applyParentUnaryOperator: (stack.Count == 0) ? applyParentUnaryOperator : null); } stack.Free(); return loweredLeft; } private static ImmutableArray<BoundExpression> CollectBinaryOperatorInterpolatedStringParts(BoundBinaryOperator node) { Debug.Assert(node.OperatorKind == BinaryOperatorKind.StringConcatenation); Debug.Assert(node.InterpolatedStringHandlerData is not null); var partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(); node.VisitBinaryOperatorInterpolatedString(partsBuilder, static (BoundInterpolatedString interpolatedString, ArrayBuilder<BoundExpression> partsBuilder) => { partsBuilder.AddRange(interpolatedString.Parts); return true; }); return partsBuilder.ToImmutableAndFree(); } private BoundExpression MakeBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, bool isPointerElementAccess = false, bool isCompoundAssignment = false, BoundUnaryOperator? applyParentUnaryOperator = null) { return MakeBinaryOperator(null, syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt, isPointerElementAccess, isCompoundAssignment, applyParentUnaryOperator); } private BoundExpression MakeBinaryOperator( BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, bool isPointerElementAccess = false, bool isCompoundAssignment = false, BoundUnaryOperator? applyParentUnaryOperator = null) { Debug.Assert(oldNode == null || (oldNode.Syntax == syntax)); if (_inExpressionLambda) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.ObjectAndStringConcatenation: case BinaryOperatorKind.StringAndObjectConcatenation: case BinaryOperatorKind.StringConcatenation: return RewriteStringConcatenation(syntax, operatorKind, loweredLeft, loweredRight, type); case BinaryOperatorKind.DelegateCombination: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__Combine); case BinaryOperatorKind.DelegateRemoval: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__Remove); case BinaryOperatorKind.DelegateEqual: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__op_Equality); case BinaryOperatorKind.DelegateNotEqual: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__op_Inequality); } } else // try to lower the expression. { if (operatorKind.IsDynamic()) { Debug.Assert(!isPointerElementAccess); if (operatorKind.IsLogical()) { return MakeDynamicLogicalBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, method, constrainedToTypeOpt, type, isCompoundAssignment, applyParentUnaryOperator); } else { Debug.Assert(method is null); return _dynamicFactory.MakeDynamicBinaryOperator(operatorKind, loweredLeft, loweredRight, isCompoundAssignment, type).ToExpression(); } } if (operatorKind.IsLifted()) { return RewriteLiftedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); } if (operatorKind.IsUserDefined()) { return LowerUserDefinedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); } switch (operatorKind.OperatorWithLogical() | operatorKind.OperandTypes()) { case BinaryOperatorKind.NullableNullEqual: case BinaryOperatorKind.NullableNullNotEqual: return RewriteNullableNullEquality(syntax, operatorKind, loweredLeft, loweredRight, type); case BinaryOperatorKind.ObjectAndStringConcatenation: case BinaryOperatorKind.StringAndObjectConcatenation: case BinaryOperatorKind.StringConcatenation: return RewriteStringConcatenation(syntax, operatorKind, loweredLeft, loweredRight, type); case BinaryOperatorKind.StringEqual: return RewriteStringEquality(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_String__op_Equality); case BinaryOperatorKind.StringNotEqual: return RewriteStringEquality(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_String__op_Inequality); case BinaryOperatorKind.DelegateCombination: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__Combine); case BinaryOperatorKind.DelegateRemoval: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__Remove); case BinaryOperatorKind.DelegateEqual: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__op_Equality); case BinaryOperatorKind.DelegateNotEqual: return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, SpecialMember.System_Delegate__op_Inequality); case BinaryOperatorKind.LogicalBoolAnd: if (loweredRight.ConstantValue == ConstantValue.True) return loweredLeft; if (loweredLeft.ConstantValue == ConstantValue.True) return loweredRight; if (loweredLeft.ConstantValue == ConstantValue.False) return loweredLeft; if (loweredRight.Kind == BoundKind.Local || loweredRight.Kind == BoundKind.Parameter) { operatorKind &= ~BinaryOperatorKind.Logical; } goto default; case BinaryOperatorKind.LogicalBoolOr: if (loweredRight.ConstantValue == ConstantValue.False) return loweredLeft; if (loweredLeft.ConstantValue == ConstantValue.False) return loweredRight; if (loweredLeft.ConstantValue == ConstantValue.True) return loweredLeft; if (loweredRight.Kind == BoundKind.Local || loweredRight.Kind == BoundKind.Parameter) { operatorKind &= ~BinaryOperatorKind.Logical; } goto default; case BinaryOperatorKind.BoolAnd: if (loweredRight.ConstantValue == ConstantValue.True) return loweredLeft; if (loweredLeft.ConstantValue == ConstantValue.True) return loweredRight; // Note that we are using IsDefaultValue instead of False. // That is just to catch cases like default(bool) or others resulting in // a default bool value, that we know to be "false" // bool? generally should not reach here, since it is handled by RewriteLiftedBinaryOperator. // Regardless, the following code should handle default(bool?) correctly since // default(bool?) & <expr> == default(bool?) with sideeffects of <expr> if (loweredLeft.IsDefaultValue()) { return _factory.MakeSequence(loweredRight, loweredLeft); } if (loweredRight.IsDefaultValue()) { return _factory.MakeSequence(loweredLeft, loweredRight); } goto default; case BinaryOperatorKind.BoolOr: if (loweredRight.ConstantValue == ConstantValue.False) return loweredLeft; if (loweredLeft.ConstantValue == ConstantValue.False) return loweredRight; goto default; case BinaryOperatorKind.BoolEqual: if (loweredLeft.ConstantValue == ConstantValue.True) return loweredRight; if (loweredRight.ConstantValue == ConstantValue.True) return loweredLeft; Debug.Assert(loweredLeft.Type is { }); Debug.Assert(loweredRight.Type is { }); if (loweredLeft.ConstantValue == ConstantValue.False) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredRight, loweredRight.Type); if (loweredRight.ConstantValue == ConstantValue.False) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredLeft, loweredLeft.Type); goto default; case BinaryOperatorKind.BoolNotEqual: if (loweredLeft.ConstantValue == ConstantValue.False) return loweredRight; if (loweredRight.ConstantValue == ConstantValue.False) return loweredLeft; Debug.Assert(loweredLeft.Type is { }); Debug.Assert(loweredRight.Type is { }); if (loweredLeft.ConstantValue == ConstantValue.True) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredRight, loweredRight.Type); if (loweredRight.ConstantValue == ConstantValue.True) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredLeft, loweredLeft.Type); goto default; case BinaryOperatorKind.BoolXor: if (loweredLeft.ConstantValue == ConstantValue.False) return loweredRight; if (loweredRight.ConstantValue == ConstantValue.False) return loweredLeft; Debug.Assert(loweredLeft.Type is { }); Debug.Assert(loweredRight.Type is { }); if (loweredLeft.ConstantValue == ConstantValue.True) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredRight, loweredRight.Type); if (loweredRight.ConstantValue == ConstantValue.True) return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, loweredLeft, loweredLeft.Type); goto default; case BinaryOperatorKind.IntLeftShift: case BinaryOperatorKind.UIntLeftShift: case BinaryOperatorKind.IntRightShift: case BinaryOperatorKind.UIntRightShift: return RewriteBuiltInShiftOperation(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, 0x1F); case BinaryOperatorKind.LongLeftShift: case BinaryOperatorKind.ULongLeftShift: case BinaryOperatorKind.LongRightShift: case BinaryOperatorKind.ULongRightShift: return RewriteBuiltInShiftOperation(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, 0x3F); case BinaryOperatorKind.DecimalAddition: case BinaryOperatorKind.DecimalSubtraction: case BinaryOperatorKind.DecimalMultiplication: case BinaryOperatorKind.DecimalDivision: case BinaryOperatorKind.DecimalRemainder: case BinaryOperatorKind.DecimalEqual: case BinaryOperatorKind.DecimalNotEqual: case BinaryOperatorKind.DecimalLessThan: case BinaryOperatorKind.DecimalLessThanOrEqual: case BinaryOperatorKind.DecimalGreaterThan: case BinaryOperatorKind.DecimalGreaterThanOrEqual: return RewriteDecimalBinaryOperation(syntax, loweredLeft, loweredRight, operatorKind); case BinaryOperatorKind.PointerAndIntAddition: case BinaryOperatorKind.PointerAndUIntAddition: case BinaryOperatorKind.PointerAndLongAddition: case BinaryOperatorKind.PointerAndULongAddition: case BinaryOperatorKind.PointerAndIntSubtraction: case BinaryOperatorKind.PointerAndUIntSubtraction: case BinaryOperatorKind.PointerAndLongSubtraction: case BinaryOperatorKind.PointerAndULongSubtraction: if (loweredRight.IsDefaultValue()) { return loweredLeft; } return RewritePointerNumericOperator(syntax, operatorKind, loweredLeft, loweredRight, type, isPointerElementAccess, isLeftPointer: true); case BinaryOperatorKind.IntAndPointerAddition: case BinaryOperatorKind.UIntAndPointerAddition: case BinaryOperatorKind.LongAndPointerAddition: case BinaryOperatorKind.ULongAndPointerAddition: if (loweredLeft.IsDefaultValue()) { return loweredRight; } return RewritePointerNumericOperator(syntax, operatorKind, loweredLeft, loweredRight, type, isPointerElementAccess, isLeftPointer: false); case BinaryOperatorKind.PointerSubtraction: return RewritePointerSubtraction(operatorKind, loweredLeft, loweredRight, type); case BinaryOperatorKind.IntAddition: case BinaryOperatorKind.UIntAddition: case BinaryOperatorKind.LongAddition: case BinaryOperatorKind.ULongAddition: if (loweredLeft.IsDefaultValue()) { return loweredRight; } if (loweredRight.IsDefaultValue()) { return loweredLeft; } goto default; case BinaryOperatorKind.IntSubtraction: case BinaryOperatorKind.LongSubtraction: case BinaryOperatorKind.UIntSubtraction: case BinaryOperatorKind.ULongSubtraction: if (loweredRight.IsDefaultValue()) { return loweredLeft; } goto default; case BinaryOperatorKind.IntMultiplication: case BinaryOperatorKind.LongMultiplication: case BinaryOperatorKind.UIntMultiplication: case BinaryOperatorKind.ULongMultiplication: if (loweredLeft.IsDefaultValue()) { return _factory.MakeSequence(loweredRight, loweredLeft); } if (loweredRight.IsDefaultValue()) { return _factory.MakeSequence(loweredLeft, loweredRight); } if (loweredLeft.ConstantValue?.UInt64Value == 1) { return loweredRight; } if (loweredRight.ConstantValue?.UInt64Value == 1) { return loweredLeft; } goto default; case BinaryOperatorKind.IntGreaterThan: case BinaryOperatorKind.IntLessThanOrEqual: if (loweredLeft.Kind == BoundKind.ArrayLength && loweredRight.IsDefaultValue()) { //array length is never negative var newOp = operatorKind == BinaryOperatorKind.IntGreaterThan ? BinaryOperatorKind.NotEqual : BinaryOperatorKind.Equal; operatorKind &= ~BinaryOperatorKind.OpMask; operatorKind |= newOp; loweredLeft = UnconvertArrayLength((BoundArrayLength)loweredLeft); } goto default; case BinaryOperatorKind.IntLessThan: case BinaryOperatorKind.IntGreaterThanOrEqual: if (loweredRight.Kind == BoundKind.ArrayLength && loweredLeft.IsDefaultValue()) { //array length is never negative var newOp = operatorKind == BinaryOperatorKind.IntLessThan ? BinaryOperatorKind.NotEqual : BinaryOperatorKind.Equal; operatorKind &= ~BinaryOperatorKind.OpMask; operatorKind |= newOp; loweredRight = UnconvertArrayLength((BoundArrayLength)loweredRight); } goto default; case BinaryOperatorKind.IntEqual: case BinaryOperatorKind.IntNotEqual: if (loweredLeft.Kind == BoundKind.ArrayLength && loweredRight.IsDefaultValue()) { loweredLeft = UnconvertArrayLength((BoundArrayLength)loweredLeft); } else if (loweredRight.Kind == BoundKind.ArrayLength && loweredLeft.IsDefaultValue()) { loweredRight = UnconvertArrayLength((BoundArrayLength)loweredRight); } goto default; default: break; } } return (oldNode != null) ? oldNode.Update(operatorKind, oldNode.ConstantValue, oldNode.Method, oldNode.ConstrainedToType, oldNode.ResultKind, loweredLeft, loweredRight, type) : new BoundBinaryOperator(syntax, operatorKind, constantValueOpt: null, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, loweredLeft, loweredRight, type); } private BoundExpression RewriteLiftedBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { var conditionalLeft = loweredLeft as BoundLoweredConditionalAccess; // NOTE: we could in theory handle side-effecting loweredRight here too // by including it as a part of whenNull, but there is a concern // that it can lead to code duplication var optimize = conditionalLeft != null && operatorKind != BinaryOperatorKind.LiftedBoolOr && operatorKind != BinaryOperatorKind.LiftedBoolAnd && !ReadIsSideeffecting(loweredRight) && (conditionalLeft.WhenNullOpt == null || conditionalLeft.WhenNullOpt.IsDefaultValue()); if (optimize) { loweredLeft = conditionalLeft!.WhenNotNull; } var result = operatorKind.IsComparison() ? operatorKind.IsUserDefined() ? LowerLiftedUserDefinedComparisonOperator(syntax, operatorKind, loweredLeft, loweredRight, method, constrainedToTypeOpt) : LowerLiftedBuiltInComparisonOperator(syntax, operatorKind, loweredLeft, loweredRight) : LowerLiftedBinaryArithmeticOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); if (optimize) { BoundExpression? whenNullOpt = null; // for all operators null-in means null-out // except for the Equal/NotEqual since null == null ==> true if (operatorKind.Operator() == BinaryOperatorKind.NotEqual || operatorKind.Operator() == BinaryOperatorKind.Equal) { Debug.Assert(loweredLeft.Type is { }); whenNullOpt = RewriteLiftedBinaryOperator(syntax, operatorKind, _factory.Default(loweredLeft.Type), loweredRight, type, method, constrainedToTypeOpt); } result = conditionalLeft!.Update( conditionalLeft.Receiver, conditionalLeft.HasValueMethodOpt, whenNotNull: result, whenNullOpt: whenNullOpt, id: conditionalLeft.Id, type: result.Type! ); } return result; } //array length produces native uint, so the node typically implies a conversion to int32/int64. //Sometimes the conversion is not necessary - i.e. when we just check for 0 //This helper removes unnecessary implied conversion from ArrayLength node. private BoundExpression UnconvertArrayLength(BoundArrayLength arrLength) { return arrLength.Update(arrLength.Expression, _factory.SpecialType(SpecialType.System_UIntPtr)); } private BoundExpression MakeDynamicLogicalBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, MethodSymbol? leftTruthOperator, TypeSymbol? constrainedToTypeOpt, TypeSymbol type, bool isCompoundAssignment, BoundUnaryOperator? applyParentUnaryOperator) { Debug.Assert(operatorKind.Operator() == BinaryOperatorKind.And || operatorKind.Operator() == BinaryOperatorKind.Or); // Dynamic logical && and || operators are lowered as follows: // left && right -> IsFalse(left) ? left : And(left, right) // left || right -> IsTrue(left) ? left : Or(left, right) // // Optimization: If the binary AND/OR is directly contained in IsFalse/IsTrue operator (parentUnaryOperator != null) // we can avoid calling IsFalse/IsTrue twice on the same object. // IsFalse(left && right) -> IsFalse(left) || IsFalse(And(left, right)) // IsTrue(left || right) -> IsTrue(left) || IsTrue(Or(left, right)) bool isAnd = operatorKind.Operator() == BinaryOperatorKind.And; // Operator to be used to test the left operand: var testOperator = isAnd ? UnaryOperatorKind.DynamicFalse : UnaryOperatorKind.DynamicTrue; // VisitUnaryOperator ensures we are never called with parentUnaryOperator != null when we can't perform the optimization. Debug.Assert(applyParentUnaryOperator == null || applyParentUnaryOperator.OperatorKind == testOperator); ConstantValue? constantLeft = loweredLeft.ConstantValue ?? UnboxConstant(loweredLeft); if (testOperator == UnaryOperatorKind.DynamicFalse && constantLeft == ConstantValue.False || testOperator == UnaryOperatorKind.DynamicTrue && constantLeft == ConstantValue.True) { Debug.Assert(leftTruthOperator == null); if (applyParentUnaryOperator != null) { // IsFalse(false && right) -> true // IsTrue(true || right) -> true return _factory.Literal(true); } else { // false && right -> box(false) // true || right -> box(true) return MakeConversionNode(loweredLeft, type, @checked: false); } } BoundExpression result; var boolean = _compilation.GetSpecialType(SpecialType.System_Boolean); // Store left to local if needed. If constant or already local we don't need a temp // since the value of left can't change until right is evaluated. BoundAssignmentOperator? tempAssignment; BoundLocal? temp; if (constantLeft == null && loweredLeft.Kind != BoundKind.Local && loweredLeft.Kind != BoundKind.Parameter) { BoundAssignmentOperator assignment; var local = _factory.StoreToTemp(loweredLeft, out assignment); loweredLeft = local; tempAssignment = assignment; temp = local; } else { tempAssignment = null; temp = null; } var op = _dynamicFactory.MakeDynamicBinaryOperator(operatorKind, loweredLeft, loweredRight, isCompoundAssignment, type).ToExpression(); // IsFalse(true) or IsTrue(false) are always false: bool leftTestIsConstantFalse = testOperator == UnaryOperatorKind.DynamicFalse && constantLeft == ConstantValue.True || testOperator == UnaryOperatorKind.DynamicTrue && constantLeft == ConstantValue.False; if (applyParentUnaryOperator != null) { // IsFalse(left && right) -> IsFalse(left) || IsFalse(And(left, right)) // IsTrue(left || right) -> IsTrue(left) || IsTrue(Or(left, right)) result = _dynamicFactory.MakeDynamicUnaryOperator(testOperator, op, boolean).ToExpression(); if (!leftTestIsConstantFalse) { BoundExpression leftTest = MakeTruthTestForDynamicLogicalOperator(syntax, loweredLeft, boolean, leftTruthOperator, constrainedToTypeOpt, negative: isAnd); result = _factory.Binary(BinaryOperatorKind.LogicalOr, boolean, leftTest, result); } } else { // left && right -> IsFalse(left) ? left : And(left, right) // left || right -> IsTrue(left) ? left : Or(left, right) if (leftTestIsConstantFalse) { result = op; } else { // We might need to box. BoundExpression leftTest = MakeTruthTestForDynamicLogicalOperator(syntax, loweredLeft, boolean, leftTruthOperator, constrainedToTypeOpt, negative: isAnd); var convertedLeft = MakeConversionNode(loweredLeft, type, @checked: false); result = _factory.Conditional(leftTest, convertedLeft, op, type); } } if (tempAssignment != null) { Debug.Assert(temp is { }); return _factory.Sequence(ImmutableArray.Create(temp.LocalSymbol), ImmutableArray.Create<BoundExpression>(tempAssignment), result); } return result; } private static ConstantValue? UnboxConstant(BoundExpression expression) { if (expression.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)expression; if (conversion.ConversionKind == ConversionKind.Boxing) { return conversion.Operand.ConstantValue; } } return null; } private BoundExpression MakeTruthTestForDynamicLogicalOperator(SyntaxNode syntax, BoundExpression loweredLeft, TypeSymbol boolean, MethodSymbol? leftTruthOperator, TypeSymbol? constrainedToTypeOpt, bool negative) { if (loweredLeft.HasDynamicType()) { Debug.Assert(leftTruthOperator == null); return _dynamicFactory.MakeDynamicUnaryOperator(negative ? UnaryOperatorKind.DynamicFalse : UnaryOperatorKind.DynamicTrue, loweredLeft, boolean).ToExpression(); } // Although the spec doesn't capture it we do the same that Dev11 does: // Use implicit conversion to Boolean if it is defined on the static type of the left operand. // If not the type has to implement IsTrue/IsFalse operator - we checked it during binding. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(); var conversion = _compilation.Conversions.ClassifyConversionFromExpression(loweredLeft, boolean, ref useSiteInfo); _diagnostics.Add(loweredLeft.Syntax, useSiteInfo); if (conversion.IsImplicit) { Debug.Assert(leftTruthOperator == null); var converted = MakeConversionNode(loweredLeft, boolean, @checked: false); if (negative) { return new BoundUnaryOperator(syntax, UnaryOperatorKind.BoolLogicalNegation, converted, ConstantValue.NotAvailable, MethodSymbol.None, constrainedToTypeOpt: null, LookupResultKind.Viable, boolean) { WasCompilerGenerated = true }; } else { return converted; } } Debug.Assert(leftTruthOperator != null); return BoundCall.Synthesized(syntax, receiverOpt: constrainedToTypeOpt is null ? null : new BoundTypeExpression(syntax, aliasOpt: null, constrainedToTypeOpt), leftTruthOperator, loweredLeft); } private BoundExpression LowerUserDefinedBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { Debug.Assert(!operatorKind.IsLogical()); if (operatorKind.IsLifted()) { return RewriteLiftedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); } // Otherwise, nothing special here. Debug.Assert(method is { }); Debug.Assert(TypeSymbol.Equals(method.ReturnType, type, TypeCompareKind.ConsiderEverything2)); return BoundCall.Synthesized(syntax, receiverOpt: constrainedToTypeOpt is null ? null : new BoundTypeExpression(syntax, aliasOpt: null, constrainedToTypeOpt), method, loweredLeft, loweredRight); } private BoundExpression? TrivialLiftedComparisonOperatorOptimizations( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { Debug.Assert(left != null); Debug.Assert(right != null); // Optimization #1: if both sides are null then the result // is either true (for equality) or false (for everything else.) bool leftAlwaysNull = NullableNeverHasValue(left); bool rightAlwaysNull = NullableNeverHasValue(right); TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); if (leftAlwaysNull && rightAlwaysNull) { return MakeLiteral(syntax, ConstantValue.Create(kind.Operator() == BinaryOperatorKind.Equal), boolType); } // Optimization #2: If both sides are non-null then we can again eliminate the lifting entirely. BoundExpression? leftNonNull = NullableAlwaysHasValue(left); BoundExpression? rightNonNull = NullableAlwaysHasValue(right); if (leftNonNull != null && rightNonNull != null) { return MakeBinaryOperator( syntax: syntax, operatorKind: kind.Unlifted(), loweredLeft: leftNonNull, loweredRight: rightNonNull, type: boolType, method: method, constrainedToTypeOpt: constrainedToTypeOpt); } // Optimization #3: If one side is null and the other is definitely not, then we generate the side effects // of the non-null side and result in true (for not-equals) or false (for everything else.) BinaryOperatorKind operatorKind = kind.Operator(); if (leftAlwaysNull && rightNonNull != null || rightAlwaysNull && leftNonNull != null) { BoundExpression result = MakeLiteral(syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.NotEqual), boolType); BoundExpression? nonNull = leftAlwaysNull ? rightNonNull : leftNonNull; Debug.Assert(nonNull is { }); if (ReadIsSideeffecting(nonNull)) { result = new BoundSequence( syntax: syntax, locals: ImmutableArray<LocalSymbol>.Empty, sideEffects: ImmutableArray.Create<BoundExpression>(nonNull), value: result, type: boolType); } return result; } // Optimization #4: If one side is null and the other is unknown, then we have three cases: // #4a: If we have x == null then that becomes !x.HasValue. // #4b: If we have x != null then that becomes x.HasValue. // #4c: If we have x OP null then that becomes side effects of x, result in false. if (leftAlwaysNull || rightAlwaysNull) { BoundExpression maybeNull = leftAlwaysNull ? right : left; if (operatorKind == BinaryOperatorKind.Equal || operatorKind == BinaryOperatorKind.NotEqual) { BoundExpression callHasValue = MakeNullableHasValue(syntax, maybeNull); BoundExpression result = operatorKind == BinaryOperatorKind.Equal ? MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, callHasValue, boolType) : callHasValue; return result; } else { BoundExpression falseExpr = MakeBooleanConstant(syntax, operatorKind == BinaryOperatorKind.NotEqual); return _factory.MakeSequence(maybeNull, falseExpr); } } return null; } private BoundExpression MakeOptimizedGetValueOrDefault(SyntaxNode syntax, BoundExpression expression) { Debug.Assert(expression.Type is { }); // If the expression is of nullable type then call GetValueOrDefault. If not, // then just use its value. if (expression.Type.IsNullableType()) { return BoundCall.Synthesized(syntax, expression, UnsafeGetNullableMethod(syntax, expression.Type, SpecialMember.System_Nullable_T_GetValueOrDefault)); } return expression; } private BoundExpression MakeBooleanConstant(SyntaxNode syntax, bool value) { return MakeLiteral(syntax, ConstantValue.Create(value), _compilation.GetSpecialType(SpecialType.System_Boolean)); } private BoundExpression MakeOptimizedHasValue(SyntaxNode syntax, BoundExpression expression) { Debug.Assert(expression.Type is { }); // If the expression is of nullable type then call HasValue. If not, then it has a value, // so return constant true. if (expression.Type.IsNullableType()) { return MakeNullableHasValue(syntax, expression); } return MakeBooleanConstant(syntax, true); } private BoundExpression MakeNullableHasValue(SyntaxNode syntax, BoundExpression expression) { Debug.Assert(expression.Type is { }); return BoundCall.Synthesized(syntax, expression, UnsafeGetNullableMethod(syntax, expression.Type, SpecialMember.System_Nullable_T_get_HasValue)); } private BoundExpression LowerLiftedBuiltInComparisonOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight) { // SPEC: For the equality operators == != : // SPEC: The lifted operator considers two null values equal and a null value unequal to // SPEC: any non-null value. If both operands are non-null the lifted operator unwraps // SPEC: the operands and applies the underlying operator to produce the bool result. // SPEC: // SPEC: For the relational operators < > <= >= : // SPEC: The lifted operator produces the value false if one or both operands // SPEC: are null. Otherwise the lifted operator unwraps the operands and // SPEC: applies the underlying operator to produce the bool result. // Note that this means that x == y is true but x <= y is false if both are null. // x <= y is not the same as (x < y) || (x == y). // Start with some simple optimizations for cases like one side being null. BoundExpression? optimized = TrivialLiftedComparisonOperatorOptimizations(syntax, kind, loweredLeft, loweredRight, method: null, constrainedToTypeOpt: null); if (optimized != null) { return optimized; } // We rewrite x == y as // // tempx = x; // tempy = y; // result = (tempx.GetValueOrDefault() == tempy.GetValueOrDefault()) & // (tempx.HasValue == tempy.HasValue); // // and x != y as // // tempx = x; // tempy = y; // result = !((tempx.GetValueOrDefault() == tempy.GetValueOrDefault()) & // (tempx.HasValue == tempy.HasValue)); // // Otherwise, we rewrite x OP y as // // tempx = x; // tempy = y; // result = (tempx.GetValueOrDefault() OP tempy.GetValueOrDefault()) & // (tempx.HasValue & tempy.HasValue); // // // Note that there is no reason to generate "&&" over "&"; the cost of // the added code for the conditional branch would be about the same as simply doing // the bitwise & in the first place. // // We have not yet optimized the case where we have a known-not-null value on one side, // and an unknown value on the other. In those cases we will still generate a temp, but // we will not generate the call to the unnecessary nullable ctor or to GetValueOrDefault. // Rather, we will generate the value's temp instead of a call to GetValueOrDefault, and generate // literal true for HasValue. The tree construction methods we call will use those constants // to eliminate unnecessary branches. BoundExpression? xNonNull = NullableAlwaysHasValue(loweredLeft); BoundExpression? yNonNull = NullableAlwaysHasValue(loweredRight); BoundLocal boundTempX = _factory.StoreToTemp(xNonNull ?? loweredLeft, out BoundAssignmentOperator tempAssignmentX); BoundLocal boundTempY = _factory.StoreToTemp(yNonNull ?? loweredRight, out BoundAssignmentOperator tempAssignmentY); BoundExpression callX_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempX); BoundExpression callY_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempY); BoundExpression callX_HasValue = MakeOptimizedHasValue(syntax, boundTempX); BoundExpression callY_HasValue = MakeOptimizedHasValue(syntax, boundTempY); BinaryOperatorKind leftOperator; BinaryOperatorKind rightOperator; BinaryOperatorKind operatorKind = kind.Operator(); switch (operatorKind) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: leftOperator = BinaryOperatorKind.Equal; rightOperator = BinaryOperatorKind.BoolEqual; break; default: leftOperator = operatorKind; rightOperator = BinaryOperatorKind.BoolAnd; break; } TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); // (tempx.GetValueOrDefault() OP tempy.GetValueOrDefault()) BoundExpression leftExpression = MakeBinaryOperator( syntax: syntax, operatorKind: leftOperator.WithType(kind.OperandTypes()), loweredLeft: callX_GetValueOrDefault, loweredRight: callY_GetValueOrDefault, type: boolType, method: null, constrainedToTypeOpt: null); // (tempx.HasValue OP tempy.HasValue) BoundExpression rightExpression = MakeBinaryOperator( syntax: syntax, operatorKind: rightOperator, loweredLeft: callX_HasValue, loweredRight: callY_HasValue, type: boolType, method: null, constrainedToTypeOpt: null); // result = (tempx.GetValueOrDefault() OP tempy.GetValueOrDefault()) & // (tempx.HasValue OP tempy.HasValue) BoundExpression binaryExpression = MakeBinaryOperator( syntax: syntax, operatorKind: BinaryOperatorKind.BoolAnd, loweredLeft: leftExpression, loweredRight: rightExpression, type: boolType, method: null, constrainedToTypeOpt: null); // result = !((tempx.GetValueOrDefault() == tempy.GetValueOrDefault()) & // (tempx.HasValue == tempy.HasValue)); if (operatorKind == BinaryOperatorKind.NotEqual) { binaryExpression = _factory.Not(binaryExpression); } // tempx = x; // tempy = y; // result = (tempx.GetValueOrDefault() == tempy.GetValueOrDefault()) & // (tempx.HasValue == tempy.HasValue); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTempX.LocalSymbol, boundTempY.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignmentX, tempAssignmentY), value: binaryExpression, type: boolType); } private BoundExpression LowerLiftedUserDefinedComparisonOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { // If both sides are null, or neither side is null, then we can do some simple optimizations. BoundExpression? optimized = TrivialLiftedComparisonOperatorOptimizations(syntax, kind, loweredLeft, loweredRight, method, constrainedToTypeOpt); if (optimized != null) { return optimized; } // Otherwise, the expression // // x == y // // becomes // // tempX = x; // tempY = y; // result = tempX.HasValue == tempY.HasValue ? // (tempX.HasValue ? // tempX.GetValueOrDefault() == tempY.GetValueOrDefault() : // true) : // false; // // // the expression // // x != y // // becomes // // tempX = x; // tempY = y; // result = tempX.HasValue == tempY.HasValue ? // (tempX.HasValue ? // tempX.GetValueOrDefault() != tempY.GetValueOrDefault() : // false) : // true; // // // For the other comparison operators <, <=, >, >=, // // x OP y // // becomes // // tempX = x; // tempY = y; // result = tempX.HasValue & tempY.HasValue ? // tempX.GetValueOrDefault() OP tempY.GetValueOrDefault() : // false; // // We have not yet optimized the case where we have a known-not-null value on one side, // and an unknown value on the other. In those cases we will still generate a temp, but // we will not generate the call to the unnecessary nullable ctor or to GetValueOrDefault. // Rather, we will generate the value's temp instead of a call to GetValueOrDefault, and generate // literal true for HasValue. The tree construction methods we call will use those constants // to eliminate unnecessary branches. BoundExpression? xNonNull = NullableAlwaysHasValue(loweredLeft); BoundExpression? yNonNull = NullableAlwaysHasValue(loweredRight); // TODO: (This TODO applies throughout this file, not just to this method.) // TODO: We might be storing a constant to this temporary that we could simply inline. // TODO: (There are other expressions that can be safely moved around other than constants // TODO: as well -- for example a boxing conversion of a constant int to object.) // TODO: Build a better temporary-storage management system that decides whether or not // TODO: to store a temporary. BoundAssignmentOperator tempAssignmentX; BoundLocal boundTempX = _factory.StoreToTemp(xNonNull ?? loweredLeft, out tempAssignmentX); BoundAssignmentOperator tempAssignmentY; BoundLocal boundTempY = _factory.StoreToTemp(yNonNull ?? loweredRight, out tempAssignmentY); BoundExpression callX_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempX); BoundExpression callY_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempY); BoundExpression callX_HasValue = MakeOptimizedHasValue(syntax, boundTempX); BoundExpression callY_HasValue = MakeOptimizedHasValue(syntax, boundTempY); // tempx.HasValue == tempy.HasValue BinaryOperatorKind conditionOperator; BinaryOperatorKind operatorKind = kind.Operator(); switch (operatorKind) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: conditionOperator = BinaryOperatorKind.BoolEqual; break; default: conditionOperator = BinaryOperatorKind.BoolAnd; break; } TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); BoundExpression condition = MakeBinaryOperator( syntax: syntax, operatorKind: conditionOperator, loweredLeft: callX_HasValue, loweredRight: callY_HasValue, type: boolType, method: null, constrainedToTypeOpt: null); // tempX.GetValueOrDefault() OP tempY.GetValueOrDefault() BoundExpression unliftedOp = MakeBinaryOperator( syntax: syntax, operatorKind: kind.Unlifted(), loweredLeft: callX_GetValueOrDefault, loweredRight: callY_GetValueOrDefault, type: boolType, method: method, constrainedToTypeOpt: constrainedToTypeOpt); BoundExpression consequence; if (operatorKind == BinaryOperatorKind.Equal || operatorKind == BinaryOperatorKind.NotEqual) { // tempx.HasValue ? tempX.GetValueOrDefault() == tempY.GetValueOrDefault() : true consequence = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: callX_HasValue, rewrittenConsequence: unliftedOp, rewrittenAlternative: MakeLiteral(syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.Equal), boolType), constantValueOpt: null, rewrittenType: boolType, isRef: false); } else { // tempX.GetValueOrDefault() OP tempY.GetValueOrDefault() consequence = unliftedOp; } // false BoundExpression alternative = MakeBooleanConstant(syntax, operatorKind == BinaryOperatorKind.NotEqual); BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: boolType, isRef: false); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTempX.LocalSymbol, boundTempY.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignmentX, tempAssignmentY), value: conditionalExpression, type: boolType); } private BoundExpression? TrivialLiftedBinaryArithmeticOptimizations( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { // We begin with a trivial optimization: if both operands are null then the // result is known to be null. Debug.Assert(left != null); Debug.Assert(right != null); // Optimization #1: if both sides are null then the result // is either true (for equality) or false (for everything else.) bool leftAlwaysNull = NullableNeverHasValue(left); bool rightAlwaysNull = NullableNeverHasValue(right); if (leftAlwaysNull && rightAlwaysNull) { // default(R?) return new BoundDefaultExpression(syntax, type); } // Optimization #2: If both sides are non-null then we can again eliminate the lifting entirely. BoundExpression? leftNonNull = NullableAlwaysHasValue(left); BoundExpression? rightNonNull = NullableAlwaysHasValue(right); if (leftNonNull != null && rightNonNull != null) { return MakeLiftedBinaryOperatorConsequence(syntax, kind, leftNonNull, rightNonNull, type, method, constrainedToTypeOpt); } return null; } private BoundExpression MakeLiftedBinaryOperatorConsequence( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { // tempX.GetValueOrDefault() OP tempY.GetValueOrDefault() BoundExpression unliftedOp = MakeBinaryOperator( syntax: syntax, operatorKind: kind.Unlifted(), loweredLeft: left, loweredRight: right, type: type.GetNullableUnderlyingType(), method: method, constrainedToTypeOpt: constrainedToTypeOpt); // new R?(tempX.GetValueOrDefault() OP tempY.GetValueOrDefault) return new BoundObjectCreationExpression( syntax, UnsafeGetNullableMethod(syntax, type, SpecialMember.System_Nullable_T__ctor), unliftedOp); } private static BoundExpression? OptimizeLiftedArithmeticOperatorOneNull( SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type) { // Here we optimize the cases where one side is known to be null. If we have // null + M() or null + new int?(M()) then we simply generate M() as a side // effect and produce null. Note that we can optimize away the unnecessary // constructor. bool leftAlwaysNull = NullableNeverHasValue(left); bool rightAlwaysNull = NullableNeverHasValue(right); Debug.Assert(!(leftAlwaysNull && rightAlwaysNull)); // We've already optimized this case. if (!(leftAlwaysNull || rightAlwaysNull)) { return null; } BoundExpression notAlwaysNull = leftAlwaysNull ? right : left; BoundExpression? neverNull = NullableAlwaysHasValue(notAlwaysNull); BoundExpression sideEffect = neverNull ?? notAlwaysNull; // If the "side effect" is a constant then we simply elide it entirely. // TODO: There are expressions other than constants that have no side effects // TODO: or elidable side effects. if (sideEffect.ConstantValue != null) { return new BoundDefaultExpression(syntax, type); } return new BoundSequence( syntax: syntax, locals: ImmutableArray<LocalSymbol>.Empty, sideEffects: ImmutableArray.Create<BoundExpression>(sideEffect), value: new BoundDefaultExpression(syntax, type), type: type); } private BoundExpression LowerLiftedBinaryArithmeticOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { // We have a lifted * / % + - << >> ^ & | binary operator. We begin with trivial // optimizations; if both sides are null or neither side is null then we can // eliminate the lifting altogether. BoundExpression? optimized = OptimizeLiftedBinaryArithmetic(syntax, kind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); if (optimized != null) { return optimized; } // We now know that neither side is null. However, we might have an operand that is known // to be non-null. If neither side is known to be non-null then we generate: // // S? tempX = left; // S? tempY = right; // R? r = tempX.HasValue & tempY.HasValue ? // new R?(tempX.GetValueOrDefault() OP tempY.GetValueOrDefault()) : // default(R?); // // If one of the operands, say the right, is non-null, then we generate: // // S? tempX = left; // S tempY = right; // not null // R? r = tempX.HasValue ? // new R?(tempX.GetValueOrDefault() OP tempY) : // default(R?); // var sideeffects = ArrayBuilder<BoundExpression>.GetInstance(); var locals = ArrayBuilder<LocalSymbol>.GetInstance(); BoundExpression? leftNeverNull = NullableAlwaysHasValue(loweredLeft); BoundExpression? rightNeverNull = NullableAlwaysHasValue(loweredRight); BoundExpression boundTempX = leftNeverNull ?? loweredLeft; boundTempX = CaptureExpressionInTempIfNeeded(boundTempX, sideeffects, locals); BoundExpression boundTempY = rightNeverNull ?? loweredRight; boundTempY = CaptureExpressionInTempIfNeeded(boundTempY, sideeffects, locals); BoundExpression callX_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempX); BoundExpression callY_GetValueOrDefault = MakeOptimizedGetValueOrDefault(syntax, boundTempY); BoundExpression callX_HasValue = MakeOptimizedHasValue(syntax, boundTempX); BoundExpression callY_HasValue = MakeOptimizedHasValue(syntax, boundTempY); // tempX.HasValue & tempY.HasValue TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); BoundExpression condition = MakeBinaryOperator(syntax, BinaryOperatorKind.BoolAnd, callX_HasValue, callY_HasValue, boolType, method: null, constrainedToTypeOpt: null); // new R?(tempX.GetValueOrDefault() OP tempY.GetValueOrDefault) BoundExpression consequence = MakeLiftedBinaryOperatorConsequence(syntax, kind, callX_GetValueOrDefault, callY_GetValueOrDefault, type, method, constrainedToTypeOpt); // default(R?) BoundExpression alternative = new BoundDefaultExpression(syntax, type); // tempX.HasValue & tempY.HasValue ? // new R?(tempX.GetValueOrDefault() OP tempY.GetValueOrDefault()) : // default(R?); BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: type, isRef: false); return new BoundSequence( syntax: syntax, locals: locals.ToImmutableAndFree(), sideEffects: sideeffects.ToImmutableAndFree(), value: conditionalExpression, type: type); } private BoundExpression CaptureExpressionInTempIfNeeded( BoundExpression operand, ArrayBuilder<BoundExpression> sideeffects, ArrayBuilder<LocalSymbol> locals, SynthesizedLocalKind kind = SynthesizedLocalKind.LoweringTemp) { if (CanChangeValueBetweenReads(operand)) { BoundAssignmentOperator tempAssignment; var tempAccess = _factory.StoreToTemp(operand, out tempAssignment, kind: kind); sideeffects.Add(tempAssignment); locals.Add(tempAccess.LocalSymbol); operand = tempAccess; } return operand; } private BoundExpression? OptimizeLiftedBinaryArithmetic( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) { BoundExpression? optimized = TrivialLiftedBinaryArithmeticOptimizations(syntax, kind, left, right, type, method, constrainedToTypeOpt); if (optimized != null) { return optimized; } // Boolean & and | operators have completely different codegen in non-trivial cases. if (kind == BinaryOperatorKind.LiftedBoolAnd || kind == BinaryOperatorKind.LiftedBoolOr) { return LowerLiftedBooleanOperator(syntax, kind, left, right); } // If one side is null then we can lower this to a side effect and a null value. optimized = OptimizeLiftedArithmeticOperatorOneNull(syntax, left, right, type); if (optimized != null) { return optimized; } // This is a bit of a complicated optimization; it is a more complex version of the // "distributed" optimizations for lifted conversions and lifted unary operators. // // Suppose we have a lifted binary operation where the left side might be null or not, // and the right side is definitely not, and moreover, it is a constant. We are particularly // concerned about this because expressions like "i++" and "i += 1" are lowered to "i = i + 1"; // it is quite common for there to be a constant on the left hand side of a lifted binop. // // Here N() returns int?: // // return N() + 1; // // In LowerLiftedBinaryOperator, above, we would optimize this as: // // int? n = N(); // int v = 1; // return n.HasValue ? new int?(n.Value + v) : new int?() // // This is unfortunate in that we generate an unnecessary temporary, but that's // not what we're going to optimize away here. This codegen is pretty good. // // Now let's suppose that instead of N(), we have a lifted operation on the left side: // // return (N1() * N2()) + 1; // // We could realize the left hand term as a lifted multiplication, produce a nullable int, // assign it to a temporary, and do the lifted addition: // // int? n1 = N1(); // int? n2 = N2(); // int? r = n1.HasValue & n2.HasValue ? new int?(n1.Value * n2.Value) : new int?(); // int v = 1; // return r.HasValue ? new int?(r.Value + v) : new int?(); // // But what is the point of the temporary r in this expansion? We can eliminate it, and // thereby eliminate two int? constructors in the process. We can realize this as: // // int? n1 = N1(); // int? n2 = N2(); // return n1.HasValue & n2.HasValue ? new int?(n1.Value * n2.Value + 1) : new int?(); // // We eliminate both the temporaries r and v. // // Now, a reasonable question at this point would be "well, suppose the expression on // the right side is not a constant, but is known to be non-null; can we do the same // optimization?" No, and here's why. Suppose we have: // // return (N1() * N2()) + V(); // // We cannot realize this as: // // int? n1 = N1(); // int? n2 = N2(); // int v = V(); // return n1.HasValue & n2.HasValue ? new int?(n1.Value * n2.Value + v) : new int?(); // // because this changes the order in which the operations happen. Before we had N1(), // N2(), the multiplication -- which might be a user-defined operator with a side effect, // or might be in a checked context and overflow -- and then V(). Now we have V() before // the multiplication, changing the order in which side effects occur. // // We could solve this problem by generating: // // int? n1 = N1(); // int? n2 = N2(); // return n1.HasValue & n2.HasValue ? new int?(n1.Value * n2.Value + V()) : (V(), new int?()); // so that the side effects of V() happen after the multiplication or before the value is // produced, but now we have generated IL for V() twice. That could be a complex expression // and the whole point of this optimization is to make less IL. // // We could, however, optimize it if the non-null V() was on the left hand side. At this // time we will not pursue that optimization. We're really just hoping to get the N1() * N2() + 1 // operation smaller; the rest is gravy. BoundExpression? nonNullRight = NullableAlwaysHasValue(right); if (nonNullRight != null && nonNullRight.ConstantValue != null && left.Kind == BoundKind.Sequence) { BoundSequence seq = (BoundSequence)left; if (seq.Value.Kind == BoundKind.ConditionalOperator) { BoundConditionalOperator conditional = (BoundConditionalOperator)seq.Value; Debug.Assert(TypeSymbol.Equals(seq.Type, conditional.Type, TypeCompareKind.ConsiderEverything2)); Debug.Assert(TypeSymbol.Equals(conditional.Type, conditional.Consequence.Type, TypeCompareKind.ConsiderEverything2)); Debug.Assert(TypeSymbol.Equals(conditional.Type, conditional.Alternative.Type, TypeCompareKind.ConsiderEverything2)); if (NullableAlwaysHasValue(conditional.Consequence) != null && NullableNeverHasValue(conditional.Alternative)) { return new BoundSequence( syntax, seq.Locals, seq.SideEffects, RewriteConditionalOperator( syntax, conditional.Condition, MakeBinaryOperator(syntax, kind, conditional.Consequence, right, type, method, constrainedToTypeOpt), MakeBinaryOperator(syntax, kind, conditional.Alternative, right, type, method, constrainedToTypeOpt), ConstantValue.NotAvailable, type, isRef: false), type); } } } return null; } private BoundExpression MakeNewNullableBoolean(SyntaxNode syntax, bool? value) { NamedTypeSymbol nullableType = _compilation.GetSpecialType(SpecialType.System_Nullable_T); TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); NamedTypeSymbol nullableBoolType = nullableType.Construct(boolType); if (value == null) { return new BoundDefaultExpression(syntax, nullableBoolType); } return new BoundObjectCreationExpression( syntax, UnsafeGetNullableMethod(syntax, nullableBoolType, SpecialMember.System_Nullable_T__ctor), MakeBooleanConstant(syntax, value.GetValueOrDefault())); } private BoundExpression? OptimizeLiftedBooleanOperatorOneNull( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { // Here we optimize the cases where one side is known to be null. bool leftAlwaysNull = NullableNeverHasValue(left); bool rightAlwaysNull = NullableNeverHasValue(right); Debug.Assert(!(leftAlwaysNull && rightAlwaysNull)); // We've already optimized this case. if (!(leftAlwaysNull || rightAlwaysNull)) { return null; } // First, if one operand is null and the other is definitely non null, then we can eliminate // all the temporaries: // // new bool?() & new bool?(B()) // new bool?() | new bool?(B()) // // can be generated as // // B() ? new bool?() : new bool?(false) // B() ? new bool?(true) : new bool?() // // respectively. BoundExpression alwaysNull = leftAlwaysNull ? left : right; BoundExpression notAlwaysNull = leftAlwaysNull ? right : left; BoundExpression? neverNull = NullableAlwaysHasValue(notAlwaysNull); Debug.Assert(alwaysNull.Type is { }); BoundExpression nullBool = new BoundDefaultExpression(syntax, alwaysNull.Type); if (neverNull != null) { BoundExpression newNullBool = MakeNewNullableBoolean(syntax, kind == BinaryOperatorKind.LiftedBoolOr); return RewriteConditionalOperator( syntax: syntax, rewrittenCondition: neverNull, rewrittenConsequence: kind == BinaryOperatorKind.LiftedBoolAnd ? nullBool : newNullBool, rewrittenAlternative: kind == BinaryOperatorKind.LiftedBoolAnd ? newNullBool : nullBool, constantValueOpt: null, rewrittenType: alwaysNull.Type, isRef: false); } // Now we optimize the case where one operand is null and the other is not. We generate // // new bool?() & M() // new bool?() | M() // // as // // bool? t = M(), t.GetValueOrDefault() ? new bool?() : t // bool? t = M(), t.GetValueOrDefault() ? t : new bool?() // // respectively. BoundAssignmentOperator tempAssignment; BoundLocal boundTemp = _factory.StoreToTemp(notAlwaysNull, out tempAssignment); BoundExpression condition = MakeOptimizedGetValueOrDefault(syntax, boundTemp); BoundExpression consequence = kind == BinaryOperatorKind.LiftedBoolAnd ? nullBool : boundTemp; BoundExpression alternative = kind == BinaryOperatorKind.LiftedBoolAnd ? boundTemp : nullBool; BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: alwaysNull.Type, isRef: false); Debug.Assert(conditionalExpression.Type is { }); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTemp.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment), value: conditionalExpression, type: conditionalExpression.Type); } private BoundExpression? OptimizeLiftedBooleanOperatorOneNonNull( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right) { // Here we optimize the cases where one side is known to be non-null. We generate: // // new bool?(B()) & N() // N() & new bool?(B()) // new bool?(B()) | N() // N() | new bool?(B()) // // as // // bool b = B(), bool? n = N(), b ? n : new bool?(false) // bool? n = N(), bool b = B(), b ? n : new bool?(false) // bool b = B(), bool? n = N(), b ? new bool?(true) : n // bool? n = N(), bool b = B(), b ? new bool?(true) : n // // respectively. BoundExpression? leftNonNull = NullableAlwaysHasValue(left); BoundExpression? rightNonNull = NullableAlwaysHasValue(right); Debug.Assert(leftNonNull == null || rightNonNull == null); // We've already optimized the case where they are both non-null. Debug.Assert(!NullableNeverHasValue(left) && !NullableNeverHasValue(right)); // We've already optimized the case where one is null. if (leftNonNull == null && rightNonNull == null) { return null; } // One is definitely not null and the other might be null. BoundAssignmentOperator tempAssignmentX; BoundLocal boundTempX = _factory.StoreToTemp(leftNonNull ?? left, out tempAssignmentX); BoundAssignmentOperator tempAssignmentY; BoundLocal boundTempY = _factory.StoreToTemp(rightNonNull ?? right, out tempAssignmentY); BoundExpression nonNullTemp = leftNonNull == null ? boundTempY : boundTempX; BoundExpression maybeNullTemp = leftNonNull == null ? boundTempX : boundTempY; BoundExpression condition = nonNullTemp; BoundExpression newNullBool = MakeNewNullableBoolean(syntax, kind == BinaryOperatorKind.LiftedBoolOr); BoundExpression consequence = kind == BinaryOperatorKind.LiftedBoolOr ? newNullBool : maybeNullTemp; BoundExpression alternative = kind == BinaryOperatorKind.LiftedBoolOr ? maybeNullTemp : newNullBool; BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: newNullBool.Type!, isRef: false); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTempX.LocalSymbol, boundTempY.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignmentX, tempAssignmentY), value: conditionalExpression, type: conditionalExpression.Type!); } private BoundExpression LowerLiftedBooleanOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight) { // x & y and x | y have special codegen if x and y are nullable Booleans. // We have already optimized cases where both operands are null or both are non-null. // Now optimize cases where one side is known to be null or one side is known to be non-null. BoundExpression? optimized = OptimizeLiftedBooleanOperatorOneNull(syntax, kind, loweredLeft, loweredRight); if (optimized != null) { return optimized; } optimized = OptimizeLiftedBooleanOperatorOneNonNull(syntax, kind, loweredLeft, loweredRight); if (optimized != null) { return optimized; } // x & y is realized as (x.GetValueOrDefault() || !(y.GetValueOrDefault() || x.HasValue)) ? y : x // x | y is realized as (x.GetValueOrDefault() || !(y.GetValueOrDefault() || x.HasValue)) ? x : y // CONSIDER: Consider realizing these using | instead of ||. // CONSIDER: The operations are extremely low cost and the added bulk to the code might not be worthwhile. BoundAssignmentOperator tempAssignmentX; BoundLocal boundTempX = _factory.StoreToTemp(loweredLeft, out tempAssignmentX); BoundAssignmentOperator tempAssignmentY; BoundLocal boundTempY = _factory.StoreToTemp(loweredRight, out tempAssignmentY); TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); MethodSymbol getValueOrDefaultX = UnsafeGetNullableMethod(syntax, boundTempX.Type, SpecialMember.System_Nullable_T_GetValueOrDefault); MethodSymbol getValueOrDefaultY = UnsafeGetNullableMethod(syntax, boundTempY.Type, SpecialMember.System_Nullable_T_GetValueOrDefault); // tempx.GetValueOrDefault() BoundExpression callX_GetValueOrDefault = BoundCall.Synthesized(syntax, boundTempX, getValueOrDefaultX); // tempy.GetValueOrDefault() BoundExpression callY_GetValueOrDefault = BoundCall.Synthesized(syntax, boundTempY, getValueOrDefaultY); // tempx.HasValue BoundExpression callX_HasValue = MakeNullableHasValue(syntax, boundTempX); // (tempy.GetValueOrDefault || tempx.HasValue) BoundExpression innerOr = MakeBinaryOperator( syntax: syntax, operatorKind: BinaryOperatorKind.LogicalBoolOr, loweredLeft: callY_GetValueOrDefault, loweredRight: callX_HasValue, type: boolType, method: null, constrainedToTypeOpt: null); // !(tempy.GetValueOrDefault || tempx.HasValue) BoundExpression invert = MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, method: null, constrainedToTypeOpt: null, innerOr, boolType); // (x.GetValueOrDefault() || !(y.GetValueOrDefault() || x.HasValue)) BoundExpression condition = MakeBinaryOperator( syntax: syntax, operatorKind: BinaryOperatorKind.LogicalBoolOr, loweredLeft: callX_GetValueOrDefault, loweredRight: invert, type: boolType, method: null, constrainedToTypeOpt: null); BoundExpression consequence = kind == BinaryOperatorKind.LiftedBoolAnd ? boundTempY : boundTempX; BoundExpression alternative = kind == BinaryOperatorKind.LiftedBoolAnd ? boundTempX : boundTempY; BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: alternative.Type!, isRef: false); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create<LocalSymbol>(boundTempX.LocalSymbol, boundTempY.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignmentX, tempAssignmentY), value: conditionalExpression, type: conditionalExpression.Type!); } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetNullableMethod"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private MethodSymbol UnsafeGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member) { return UnsafeGetNullableMethod(syntax, nullableType, member, _compilation, _diagnostics); } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetNullableMethod"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private static MethodSymbol UnsafeGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { var nullableType2 = nullableType as NamedTypeSymbol; Debug.Assert(nullableType2 is { }); return UnsafeGetSpecialTypeMethod(syntax, member, compilation, diagnostics).AsMember(nullableType2); } private bool TryGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member, out MethodSymbol result) { var nullableType2 = (NamedTypeSymbol)nullableType; if (TryGetSpecialTypeMethod(syntax, member, out result)) { result = result.AsMember(nullableType2); return true; } return false; } private BoundExpression RewriteNullableNullEquality( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType) { // This handles the case where we have a nullable user-defined struct type compared against null, eg: // // struct S {} ... S? s = whatever; if (s != null) // // If S does not define an overloaded != operator then this is lowered to s.HasValue. // // If the type already has a user-defined or built-in operator then comparing to null is // treated as a lifted equality operator. Debug.Assert(loweredLeft != null); Debug.Assert(loweredRight != null); Debug.Assert((object)returnType != null); Debug.Assert(returnType.SpecialType == SpecialType.System_Boolean); Debug.Assert(loweredLeft.IsLiteralNull() != loweredRight.IsLiteralNull()); BoundExpression nullable = loweredRight.IsLiteralNull() ? loweredLeft : loweredRight; // If the other side is known to always be null then we can simply generate true or false, as appropriate. if (NullableNeverHasValue(nullable)) { return MakeLiteral(syntax, ConstantValue.Create(kind == BinaryOperatorKind.NullableNullEqual), returnType); } BoundExpression? nonNullValue = NullableAlwaysHasValue(nullable); if (nonNullValue != null) { // We have something like "if (new int?(M()) != null)". We can optimize this to // evaluate M() for its side effects and then result in true or false, as appropriate. // TODO: If the expression has no side effects then it can be optimized away here as well. return new BoundSequence( syntax: syntax, locals: ImmutableArray<LocalSymbol>.Empty, sideEffects: ImmutableArray.Create<BoundExpression>(nonNullValue), value: MakeBooleanConstant(syntax, kind == BinaryOperatorKind.NullableNullNotEqual), type: returnType); } // arr?.Length == null var conditionalAccess = nullable as BoundLoweredConditionalAccess; if (conditionalAccess != null && (conditionalAccess.WhenNullOpt == null || conditionalAccess.WhenNullOpt.IsDefaultValue())) { BoundExpression whenNotNull = RewriteNullableNullEquality( syntax, kind, conditionalAccess.WhenNotNull, loweredLeft.IsLiteralNull() ? loweredLeft : loweredRight, returnType); var whenNull = kind == BinaryOperatorKind.NullableNullEqual ? MakeBooleanConstant(syntax, true) : null; return conditionalAccess.Update(conditionalAccess.Receiver, conditionalAccess.HasValueMethodOpt, whenNotNull, whenNull, conditionalAccess.Id, whenNotNull.Type!); } BoundExpression call = MakeNullableHasValue(syntax, nullable); BoundExpression result = kind == BinaryOperatorKind.NullableNullNotEqual ? call : new BoundUnaryOperator(syntax, UnaryOperatorKind.BoolLogicalNegation, call, ConstantValue.NotAvailable, null, constrainedToTypeOpt: null, LookupResultKind.Viable, returnType); return result; } private BoundExpression RewriteStringEquality(BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, SpecialMember member) { if (oldNode != null && (loweredLeft.ConstantValue == ConstantValue.Null || loweredRight.ConstantValue == ConstantValue.Null)) { return oldNode.Update(operatorKind, oldNode.ConstantValue, oldNode.Method, oldNode.ConstrainedToType, oldNode.ResultKind, loweredLeft, loweredRight, type); } var method = UnsafeGetSpecialTypeMethod(syntax, member); Debug.Assert((object)method != null); return BoundCall.Synthesized(syntax, receiverOpt: null, method, loweredLeft, loweredRight); } private BoundExpression RewriteDelegateOperation(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, SpecialMember member) { MethodSymbol method; if (operatorKind == BinaryOperatorKind.DelegateEqual || operatorKind == BinaryOperatorKind.DelegateNotEqual) { method = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member); if (loweredRight.IsLiteralNull() || loweredLeft.IsLiteralNull() || (object)(method = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member)) == null) { // use reference equality in the absence of overloaded operators for System.Delegate. operatorKind = (operatorKind & (~BinaryOperatorKind.Delegate)) | BinaryOperatorKind.Object; return new BoundBinaryOperator(syntax, operatorKind, constantValueOpt: null, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Empty, loweredLeft, loweredRight, type); } } else { method = UnsafeGetSpecialTypeMethod(syntax, member); } Debug.Assert((object)method != null); BoundExpression call = _inExpressionLambda ? new BoundBinaryOperator(syntax, operatorKind, null, method, constrainedToTypeOpt: null, default(LookupResultKind), loweredLeft, loweredRight, method.ReturnType) : (BoundExpression)BoundCall.Synthesized(syntax, receiverOpt: null, method, loweredLeft, loweredRight); BoundExpression result = method.ReturnType.SpecialType == SpecialType.System_Delegate ? MakeConversionNode(syntax, call, Conversion.ExplicitReference, type, @checked: false) : call; return result; } private BoundExpression RewriteDecimalBinaryOperation(SyntaxNode syntax, BoundExpression loweredLeft, BoundExpression loweredRight, BinaryOperatorKind operatorKind) { Debug.Assert(loweredLeft.Type is { SpecialType: SpecialType.System_Decimal }); Debug.Assert(loweredRight.Type is { SpecialType: SpecialType.System_Decimal }); SpecialMember member; switch (operatorKind) { case BinaryOperatorKind.DecimalAddition: member = SpecialMember.System_Decimal__op_Addition; break; case BinaryOperatorKind.DecimalSubtraction: member = SpecialMember.System_Decimal__op_Subtraction; break; case BinaryOperatorKind.DecimalMultiplication: member = SpecialMember.System_Decimal__op_Multiply; break; case BinaryOperatorKind.DecimalDivision: member = SpecialMember.System_Decimal__op_Division; break; case BinaryOperatorKind.DecimalRemainder: member = SpecialMember.System_Decimal__op_Modulus; break; case BinaryOperatorKind.DecimalEqual: member = SpecialMember.System_Decimal__op_Equality; break; case BinaryOperatorKind.DecimalNotEqual: member = SpecialMember.System_Decimal__op_Inequality; break; case BinaryOperatorKind.DecimalLessThan: member = SpecialMember.System_Decimal__op_LessThan; break; case BinaryOperatorKind.DecimalLessThanOrEqual: member = SpecialMember.System_Decimal__op_LessThanOrEqual; break; case BinaryOperatorKind.DecimalGreaterThan: member = SpecialMember.System_Decimal__op_GreaterThan; break; case BinaryOperatorKind.DecimalGreaterThanOrEqual: member = SpecialMember.System_Decimal__op_GreaterThanOrEqual; break; default: throw ExceptionUtilities.UnexpectedValue(operatorKind); } // call Operator (left, right) var method = UnsafeGetSpecialTypeMethod(syntax, member); Debug.Assert((object)method != null); return BoundCall.Synthesized(syntax, receiverOpt: null, method, loweredLeft, loweredRight); } private BoundExpression MakeNullCheck(SyntaxNode syntax, BoundExpression rewrittenExpr, BinaryOperatorKind operatorKind) { Debug.Assert((operatorKind == BinaryOperatorKind.Equal) || (operatorKind == BinaryOperatorKind.NotEqual) || (operatorKind == BinaryOperatorKind.NullableNullEqual) || (operatorKind == BinaryOperatorKind.NullableNullNotEqual)); TypeSymbol? exprType = rewrittenExpr.Type; // Don't even call this method if the expression cannot be nullable. Debug.Assert( exprType is null || exprType.IsNullableTypeOrTypeParameter() || !exprType.IsValueType || exprType.IsPointerOrFunctionPointer()); TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); // Fold compile-time comparisons. if (rewrittenExpr.ConstantValue != null) { switch (operatorKind) { case BinaryOperatorKind.Equal: return MakeLiteral(syntax, ConstantValue.Create(rewrittenExpr.ConstantValue.IsNull, ConstantValueTypeDiscriminator.Boolean), boolType); case BinaryOperatorKind.NotEqual: return MakeLiteral(syntax, ConstantValue.Create(!rewrittenExpr.ConstantValue.IsNull, ConstantValueTypeDiscriminator.Boolean), boolType); } } TypeSymbol objectType = _compilation.GetSpecialType(SpecialType.System_Object); if (exprType is { }) { if (exprType.Kind == SymbolKind.TypeParameter) { // Box type parameters. rewrittenExpr = MakeConversionNode(syntax, rewrittenExpr, Conversion.Boxing, objectType, @checked: false); } else if (exprType.IsNullableType()) { operatorKind |= BinaryOperatorKind.NullableNull; } } return MakeBinaryOperator( syntax, operatorKind, rewrittenExpr, MakeLiteral(syntax, ConstantValue.Null, objectType), boolType, method: null, constrainedToTypeOpt: null); } /// <summary> /// Spec section 7.9: if the left operand is int or uint, mask the right operand with 0x1F; /// if the left operand is long or ulong, mask the right operand with 0x3F. /// </summary> private BoundExpression RewriteBuiltInShiftOperation( BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, int rightMask) { SyntaxNode rightSyntax = loweredRight.Syntax; ConstantValue? rightConstantValue = loweredRight.ConstantValue; Debug.Assert(loweredRight.Type is { }); TypeSymbol rightType = loweredRight.Type; Debug.Assert(rightType.SpecialType == SpecialType.System_Int32); if (rightConstantValue != null && rightConstantValue.IsIntegral) { int shiftAmount = rightConstantValue.Int32Value & rightMask; if (shiftAmount == 0) { return loweredLeft; } loweredRight = MakeLiteral(rightSyntax, ConstantValue.Create(shiftAmount), rightType); } else { BinaryOperatorKind andOperatorKind = (operatorKind & ~BinaryOperatorKind.OpMask) | BinaryOperatorKind.And; loweredRight = new BoundBinaryOperator( rightSyntax, andOperatorKind, null, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, loweredRight, MakeLiteral(rightSyntax, ConstantValue.Create(rightMask), rightType), rightType); } return oldNode == null ? new BoundBinaryOperator( syntax, operatorKind, null, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, loweredLeft, loweredRight, type) : oldNode.Update( operatorKind, null, methodOpt: null, constrainedToTypeOpt: null, oldNode.ResultKind, loweredLeft, loweredRight, type); } private BoundExpression RewritePointerNumericOperator( SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType, bool isPointerElementAccess, bool isLeftPointer) { if (isLeftPointer) { Debug.Assert(loweredLeft.Type is { TypeKind: TypeKind.Pointer }); loweredRight = MakeSizeOfMultiplication(loweredRight, (PointerTypeSymbol)loweredLeft.Type, kind.IsChecked()); } else { Debug.Assert(loweredRight.Type is { TypeKind: TypeKind.Pointer }); loweredLeft = MakeSizeOfMultiplication(loweredLeft, (PointerTypeSymbol)loweredRight.Type, kind.IsChecked()); } if (isPointerElementAccess) { Debug.Assert(kind.Operator() == BinaryOperatorKind.Addition); // NOTE: This is here to persist a bug in Dev10. checked(p[n]) should be equivalent to checked(*(p + n)), // but Dev10 omits the check on the addition (though it retains the check on the multiplication of n by // the size). kind = kind & ~BinaryOperatorKind.Checked; } return new BoundBinaryOperator( syntax, kind, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, loweredLeft, loweredRight, returnType); } /// <summary> /// This rather confusing method tries to reproduce the functionality of ExpressionBinder::bindPtrAddMul and /// ExpressionBinder::bindPtrMul. The basic idea is that we have a numeric expression, x, and a pointer type, /// T*, and we want to multiply x by sizeof(T). Unfortunately, we need to stick in some conversions to make /// everything work. /// /// 1) If x is an int, then convert it to an IntPtr (i.e. a native int). Dev10 offers no explanation (ExpressionBinder::bindPtrMul). /// 2) Do overload resolution based on the (possibly converted) type of X and int (the type of sizeof(T)). /// 3) If the result type of the chosen multiplication operator is signed, convert the product to IntPtr; /// otherwise, convert the product to UIntPtr. /// </summary> private BoundExpression MakeSizeOfMultiplication(BoundExpression numericOperand, PointerTypeSymbol pointerType, bool isChecked) { var sizeOfExpression = _factory.Sizeof(pointerType.PointedAtType); Debug.Assert(sizeOfExpression.Type is { SpecialType: SpecialType.System_Int32 }); // Common case: adding or subtracting one (e.g. for ++) if (numericOperand.ConstantValue?.UInt64Value == 1) { // We could convert this to a native int (as the unoptimized multiplication would be), // but that would be a no-op (int to native int), so don't bother. return sizeOfExpression; } Debug.Assert(numericOperand.Type is { }); var numericSpecialType = numericOperand.Type.SpecialType; // Optimization: the size is exactly one byte, then multiplication is unnecessary. if (sizeOfExpression.ConstantValue?.Int32Value == 1) { // As in ExpressionBinder::bindPtrAddMul, we apply the following conversions: // int -> int (add allows int32 operands and will extend to native int if necessary) // uint -> native uint (add will sign-extend 32bit operand on 64bit, we do not want that happening) // long -> native int // ulong -> native uint // Note that these are not the types we would see if we let the multiplication happen. // ACASEY: These rules are inferred from the native compiler. SpecialType destinationType = numericSpecialType; switch (numericSpecialType) { case SpecialType.System_Int32: // add operator can take int32 and extend to 64bit if necessary // however in a case of checked operation, the operation is treated as unsigned with overflow ( add.ovf.un , sub.ovf.un ) // the IL spec is a bit vague whether JIT should sign or zero extend the shorter operand in such case // and there could be inconsistencies in implementation or bugs. // As a result, in checked contexts, we will force sign-extending cast to be sure if (isChecked) { var constVal = numericOperand.ConstantValue; if (constVal == null || constVal.Int32Value < 0) { destinationType = SpecialType.System_IntPtr; } } break; case SpecialType.System_UInt32: { // add operator treats operands as signed and will sign-extend on x64 // to prevent sign-extending, convert the operand to unsigned native int. var constVal = numericOperand.ConstantValue; if (constVal == null || constVal.UInt32Value > int.MaxValue) { destinationType = SpecialType.System_UIntPtr; } } break; case SpecialType.System_Int64: destinationType = SpecialType.System_IntPtr; break; case SpecialType.System_UInt64: destinationType = SpecialType.System_UIntPtr; break; default: throw ExceptionUtilities.UnexpectedValue(numericSpecialType); } return destinationType == numericSpecialType ? numericOperand : _factory.Convert(_factory.SpecialType(destinationType), numericOperand, Conversion.IntegerToPointer); } BinaryOperatorKind multiplicationKind = BinaryOperatorKind.Multiplication; TypeSymbol multiplicationResultType; TypeSymbol convertedMultiplicationResultType; switch (numericSpecialType) { case SpecialType.System_Int32: { TypeSymbol nativeIntType = _factory.SpecialType(SpecialType.System_IntPtr); // From ExpressionBinder::bindPtrMul: // this multiplication needs to be done as natural ints, but since a (int * natint) ==> natint, // we only need to promote one side numericOperand = _factory.Convert(nativeIntType, numericOperand, Conversion.IntegerToPointer, isChecked); multiplicationKind |= BinaryOperatorKind.Int; //i.e. signed multiplicationResultType = nativeIntType; convertedMultiplicationResultType = nativeIntType; break; } case SpecialType.System_UInt32: { TypeSymbol longType = _factory.SpecialType(SpecialType.System_Int64); TypeSymbol nativeIntType = _factory.SpecialType(SpecialType.System_IntPtr); // We're multiplying a uint by an int, so promote both to long (same as normal operator overload resolution). numericOperand = _factory.Convert(longType, numericOperand, Conversion.ExplicitNumeric, isChecked); sizeOfExpression = _factory.Convert(longType, sizeOfExpression, Conversion.ExplicitNumeric, isChecked); multiplicationKind |= BinaryOperatorKind.Long; multiplicationResultType = longType; convertedMultiplicationResultType = nativeIntType; break; } case SpecialType.System_Int64: { TypeSymbol longType = _factory.SpecialType(SpecialType.System_Int64); TypeSymbol nativeIntType = _factory.SpecialType(SpecialType.System_IntPtr); // We're multiplying a long by an int, so promote the int to long (same as normal operator overload resolution). sizeOfExpression = _factory.Convert(longType, sizeOfExpression, Conversion.ExplicitNumeric, isChecked); multiplicationKind |= BinaryOperatorKind.Long; multiplicationResultType = longType; convertedMultiplicationResultType = nativeIntType; break; } case SpecialType.System_UInt64: { TypeSymbol ulongType = _factory.SpecialType(SpecialType.System_UInt64); TypeSymbol nativeUIntType = _factory.SpecialType(SpecialType.System_UIntPtr); // We're multiplying a ulong by an int, so promote the int to ulong (same as normal operator overload resolution). sizeOfExpression = _factory.Convert(ulongType, sizeOfExpression, Conversion.ExplicitNumeric, isChecked); multiplicationKind |= BinaryOperatorKind.ULong; multiplicationResultType = ulongType; convertedMultiplicationResultType = nativeUIntType; //unsigned since multiplicationResultType is unsigned break; } default: { throw ExceptionUtilities.UnexpectedValue(numericSpecialType); } } if (isChecked) { multiplicationKind |= BinaryOperatorKind.Checked; } var multiplication = _factory.Binary(multiplicationKind, multiplicationResultType, numericOperand, sizeOfExpression); return TypeSymbol.Equals(convertedMultiplicationResultType, multiplicationResultType, TypeCompareKind.ConsiderEverything2) ? multiplication : _factory.Convert(convertedMultiplicationResultType, multiplication, Conversion.IntegerToPointer); // NOTE: for some reason, dev10 doesn't check this conversion. } private BoundExpression RewritePointerSubtraction( BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType) { Debug.Assert(loweredLeft.Type is { TypeKind: TypeKind.Pointer }); Debug.Assert(loweredRight.Type is { TypeKind: TypeKind.Pointer }); Debug.Assert(returnType.SpecialType == SpecialType.System_Int64); PointerTypeSymbol pointerType = (PointerTypeSymbol)loweredLeft.Type; var sizeOfExpression = _factory.Sizeof(pointerType.PointedAtType); // NOTE: to match dev10, the result of the subtraction is treated as an IntPtr // and then the result of the division is converted to long. // NOTE: dev10 doesn't optimize away division by 1. return _factory.Convert( returnType, _factory.Binary( BinaryOperatorKind.Division, _factory.SpecialType(SpecialType.System_IntPtr), _factory.Binary( kind & ~BinaryOperatorKind.Checked, // For some reason, dev10 never checks for subtraction overflow. returnType, loweredLeft, loweredRight), sizeOfExpression), Conversion.PointerToInteger); } } }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { internal sealed partial class CSharpOperationFactory { private readonly SemanticModel _semanticModel; public CSharpOperationFactory(SemanticModel semanticModel) { _semanticModel = semanticModel; } [return: NotNullIfNotNull("boundNode")] public IOperation? Create(BoundNode? boundNode) { if (boundNode == null) { return null; } switch (boundNode.Kind) { case BoundKind.DeconstructValuePlaceholder: return CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); case BoundKind.DeconstructionAssignmentOperator: return CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); case BoundKind.Call: return CreateBoundCallOperation((BoundCall)boundNode); case BoundKind.Local: return CreateBoundLocalOperation((BoundLocal)boundNode); case BoundKind.FieldAccess: return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); case BoundKind.PropertyAccess: return CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); case BoundKind.IndexerAccess: return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); case BoundKind.EventAccess: return CreateBoundEventAccessOperation((BoundEventAccess)boundNode); case BoundKind.EventAssignmentOperator: return CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); case BoundKind.Parameter: return CreateBoundParameterOperation((BoundParameter)boundNode); case BoundKind.Literal: return CreateBoundLiteralOperation((BoundLiteral)boundNode); case BoundKind.DynamicInvocation: return CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); case BoundKind.DynamicIndexerAccess: return CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); case BoundKind.ObjectCreationExpression: return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); case BoundKind.WithExpression: return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); case BoundKind.DynamicObjectCreationExpression: return CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); case BoundKind.ObjectInitializerExpression: return CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); case BoundKind.CollectionInitializerExpression: return CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); case BoundKind.ObjectInitializerMember: return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); case BoundKind.CollectionElementInitializer: return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); case BoundKind.DynamicObjectInitializerMember: return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); case BoundKind.DynamicMemberAccess: return CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); case BoundKind.DynamicCollectionElementInitializer: return CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); case BoundKind.UnboundLambda: return CreateUnboundLambdaOperation((UnboundLambda)boundNode); case BoundKind.Lambda: return CreateBoundLambdaOperation((BoundLambda)boundNode); case BoundKind.Conversion: return CreateBoundConversionOperation((BoundConversion)boundNode); case BoundKind.AsOperator: return CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); case BoundKind.IsOperator: return CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); case BoundKind.SizeOfOperator: return CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); case BoundKind.TypeOfOperator: return CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); case BoundKind.ArrayCreation: return CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); case BoundKind.ArrayInitialization: return CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); case BoundKind.DefaultLiteral: return CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); case BoundKind.DefaultExpression: return CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); case BoundKind.BaseReference: return CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); case BoundKind.ThisReference: return CreateBoundThisReferenceOperation((BoundThisReference)boundNode); case BoundKind.AssignmentOperator: return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); case BoundKind.CompoundAssignmentOperator: return CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); case BoundKind.IncrementOperator: return CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); case BoundKind.BadExpression: return CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); case BoundKind.NewT: return CreateBoundNewTOperation((BoundNewT)boundNode); case BoundKind.NoPiaObjectCreationExpression: return CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); case BoundKind.UnaryOperator: return CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); case BoundKind.BinaryOperator: case BoundKind.UserDefinedConditionalLogicalOperator: return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); case BoundKind.TupleBinaryOperator: return CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); case BoundKind.ConditionalOperator: return CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); case BoundKind.NullCoalescingOperator: return CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); case BoundKind.AwaitExpression: return CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); case BoundKind.ArrayAccess: return CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); case BoundKind.NameOfOperator: return CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); case BoundKind.ThrowExpression: return CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); case BoundKind.AddressOfOperator: return CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); case BoundKind.ImplicitReceiver: return CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); case BoundKind.ConditionalAccess: return CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); case BoundKind.ConditionalReceiver: return CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); case BoundKind.FieldEqualsValue: return CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); case BoundKind.PropertyEqualsValue: return CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); case BoundKind.ParameterEqualsValue: return CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); case BoundKind.Block: return CreateBoundBlockOperation((BoundBlock)boundNode); case BoundKind.ContinueStatement: return CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); case BoundKind.BreakStatement: return CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); case BoundKind.YieldBreakStatement: return CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); case BoundKind.GotoStatement: return CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); case BoundKind.NoOpStatement: return CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); case BoundKind.IfStatement: return CreateBoundIfStatementOperation((BoundIfStatement)boundNode); case BoundKind.WhileStatement: return CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); case BoundKind.DoStatement: return CreateBoundDoStatementOperation((BoundDoStatement)boundNode); case BoundKind.ForStatement: return CreateBoundForStatementOperation((BoundForStatement)boundNode); case BoundKind.ForEachStatement: return CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); case BoundKind.TryStatement: return CreateBoundTryStatementOperation((BoundTryStatement)boundNode); case BoundKind.CatchBlock: return CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); case BoundKind.FixedStatement: return CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); case BoundKind.UsingStatement: return CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); case BoundKind.ThrowStatement: return CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); case BoundKind.ReturnStatement: return CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); case BoundKind.YieldReturnStatement: return CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); case BoundKind.LockStatement: return CreateBoundLockStatementOperation((BoundLockStatement)boundNode); case BoundKind.BadStatement: return CreateBoundBadStatementOperation((BoundBadStatement)boundNode); case BoundKind.LocalDeclaration: return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); case BoundKind.LabelStatement: return CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); case BoundKind.LabeledStatement: return CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); case BoundKind.ExpressionStatement: return CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return CreateBoundTupleOperation((BoundTupleExpression)boundNode); case BoundKind.UnconvertedInterpolatedString: throw ExceptionUtilities.Unreachable; case BoundKind.InterpolatedString: return CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); case BoundKind.StringInsert: return CreateBoundInterpolationOperation((BoundStringInsert)boundNode); case BoundKind.LocalFunctionStatement: return CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); case BoundKind.AnonymousObjectCreationExpression: return CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); case BoundKind.AnonymousPropertyDeclaration: throw ExceptionUtilities.Unreachable; case BoundKind.ConstantPattern: return CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); case BoundKind.DeclarationPattern: return CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); case BoundKind.RecursivePattern: return CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); case BoundKind.ITuplePattern: return CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); case BoundKind.DiscardPattern: return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); case BoundKind.BinaryPattern: return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); case BoundKind.NegatedPattern: return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); case BoundKind.RelationalPattern: return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); case BoundKind.TypePattern: return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); case BoundKind.SwitchStatement: return CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); case BoundKind.SwitchLabel: return CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); case BoundKind.IsPatternExpression: return CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); case BoundKind.QueryClause: return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); case BoundKind.DelegateCreationExpression: return CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); case BoundKind.RangeVariable: return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); case BoundKind.ConstructorMethodBody: return CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); case BoundKind.NonConstructorMethodBody: return CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); case BoundKind.DiscardExpression: return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); case BoundKind.NullCoalescingAssignmentOperator: return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); case BoundKind.FromEndIndexExpression: return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); case BoundKind.RangeExpression: return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); case BoundKind.SwitchSection: return CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); case BoundKind.UnconvertedConditionalOperator: throw ExceptionUtilities.Unreachable; case BoundKind.UnconvertedSwitchExpression: throw ExceptionUtilities.Unreachable; case BoundKind.ConvertedSwitchExpression: return CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); case BoundKind.SwitchExpressionArm: return CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); case BoundKind.ObjectOrCollectionValuePlaceholder: return CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); case BoundKind.FunctionPointerInvocation: return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); case BoundKind.UnconvertedAddressOfOperator: return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); case BoundKind.Attribute: case BoundKind.ArgList: case BoundKind.ArgListOperator: case BoundKind.ConvertedStackAllocExpression: case BoundKind.FixedLocalCollectionInitializer: case BoundKind.GlobalStatementInitializer: case BoundKind.HostObjectMemberReference: case BoundKind.MakeRefOperator: case BoundKind.MethodGroup: case BoundKind.NamespaceExpression: case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PreviousSubmissionReference: case BoundKind.RefTypeOperator: case BoundKind.RefValueOperator: case BoundKind.Sequence: case BoundKind.StackAllocArrayCreation: case BoundKind.TypeExpression: case BoundKind.TypeOrValueExpression: case BoundKind.IndexOrRangePatternIndexerAccess: ConstantValue? constantValue = (boundNode as BoundExpression)?.ConstantValue; bool isImplicit = boundNode.WasCompilerGenerated; if (!isImplicit) { switch (boundNode.Kind) { case BoundKind.FixedLocalCollectionInitializer: isImplicit = true; break; } } ImmutableArray<IOperation> children = GetIOperationChildren(boundNode); return new NoneOperation(children, _semanticModel, boundNode.Syntax, type: null, constantValue, isImplicit: isImplicit); default: // If you're hitting this because the IOperation test hook has failed, see // <roslyn-root>/docs/Compilers/IOperation Test Hook.md for instructions on how to fix. throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } public ImmutableArray<TOperation> CreateFromArray<TBoundNode, TOperation>(ImmutableArray<TBoundNode> boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation { if (boundNodes.IsDefault) { return ImmutableArray<TOperation>.Empty; } var builder = ArrayBuilder<TOperation>.GetInstance(boundNodes.Length); foreach (var node in boundNodes) { builder.AddIfNotNull((TOperation)Create(node)); } return builder.ToImmutableAndFree(); } private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) { return new MethodBodyOperation( (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) { return new ConstructorBodyOperation( boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal ImmutableArray<IOperation> GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) { var children = boundNodeWithChildren.Children; if (children.IsDefaultOrEmpty) { return ImmutableArray<IOperation>.Empty; } var builder = ArrayBuilder<IOperation>.GetInstance(children.Length); foreach (BoundNode? childNode in children) { if (childNode == null) { continue; } IOperation operation = Create(childNode); builder.Add(operation); } return builder.ToImmutableAndFree(); } internal ImmutableArray<IVariableDeclaratorOperation> CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (declarationSyntax as VariableDeclarationSyntax)?.Variables[0] ?? declarationSyntax)); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var multipleDeclaration = (BoundMultipleLocalDeclarationsBase)declaration; var builder = ArrayBuilder<IVariableDeclaratorOperation>.GetInstance(multipleDeclaration.LocalDeclarations.Length); foreach (var decl in multipleDeclaration.LocalDeclarations) { builder.Add((IVariableDeclaratorOperation)CreateVariableDeclaratorInternal(decl, decl.Syntax)); } return builder.ToImmutableAndFree(); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) { SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; ITypeSymbol? type = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructValuePlaceholder.WasCompilerGenerated; return new PlaceholderOperation(PlaceholderKind.Unspecified, _semanticModel, syntax, type, isImplicit); } private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) { IOperation target = Create(boundDeconstructionAssignmentOperator.Left); // Skip the synthetic deconstruction conversion wrapping the right operand. This is a compiler-generated conversion that we don't want to reflect // in the public API because it's an implementation detail. IOperation value = Create(boundDeconstructionAssignmentOperator.Right.Operand); SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; ITypeSymbol? type = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructionAssignmentOperator.WasCompilerGenerated; return new DeconstructionAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCallOperation(BoundCall boundCall) { MethodSymbol targetMethod = boundCall.Method; SyntaxNode syntax = boundCall.Syntax; ITypeSymbol? type = boundCall.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCall.ConstantValue; bool isImplicit = boundCall.WasCompilerGenerated; if (!boundCall.OriginalMethodsOpt.IsDefault || IsMethodInvalid(boundCall.ResultKind, targetMethod)) { ImmutableArray<IOperation> children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCall).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(targetMethod, boundCall.ReceiverOpt); IOperation? receiver = CreateReceiverOperation(boundCall.ReceiverOpt, targetMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCall); return new InvocationOperation(targetMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) { ITypeSymbol? type = boundFunctionPointerInvocation.GetPublicTypeSymbol(); SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; bool isImplicit = boundFunctionPointerInvocation.WasCompilerGenerated; ImmutableArray<IOperation> children; if (boundFunctionPointerInvocation.ResultKind != LookupResultKind.Viable) { children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } children = GetIOperationChildren(boundFunctionPointerInvocation); return new NoneOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) { return new AddressOfOperation( Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); } internal ImmutableArray<IOperation> CreateIgnoredDimensions(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { BoundTypeExpression? declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); return CreateFromArray<BoundExpression, IOperation>(declaredTypeOpt.BoundDimensionsOpt); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var declarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; ImmutableArray<BoundExpression> dimensions; if (declarations.Length > 0) { BoundTypeExpression? declaredTypeOpt = declarations[0].DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); dimensions = declaredTypeOpt.BoundDimensionsOpt; } else { dimensions = ImmutableArray<BoundExpression>.Empty; } return CreateFromArray<BoundExpression, IOperation>(dimensions); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) { ILocalSymbol local = boundLocal.LocalSymbol.GetPublicSymbol(); bool isDeclaration = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; SyntaxNode syntax = boundLocal.Syntax; ITypeSymbol? type = boundLocal.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLocal.ConstantValue; bool isImplicit = boundLocal.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation localReference = CreateBoundLocalOperation(boundLocal, createDeclaration: false); return new DeclarationExpressionOperation(localReference, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } return new LocalReferenceOperation(local, isDeclaration, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) { IFieldSymbol field = boundFieldAccess.FieldSymbol.GetPublicSymbol(); bool isDeclaration = boundFieldAccess.IsDeclaration; SyntaxNode syntax = boundFieldAccess.Syntax; ITypeSymbol? type = boundFieldAccess.GetPublicTypeSymbol(); ConstantValue? constantValue = boundFieldAccess.ConstantValue; bool isImplicit = boundFieldAccess.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation fieldAccess = CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false); return new DeclarationExpressionOperation(fieldAccess, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } IOperation? instance = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); return new FieldReferenceOperation(field, isDeclaration, instance, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) { switch (boundNode) { case BoundPropertyAccess boundPropertyAccess: return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); case BoundObjectInitializerMember boundObjectInitializerMember: return boundObjectInitializerMember.MemberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); case BoundIndexerAccess boundIndexerAccess: return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); default: throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) { IOperation? instance = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); var arguments = ImmutableArray<IArgumentOperation>.Empty; IPropertySymbol property = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); SyntaxNode syntax = boundPropertyAccess.Syntax; ITypeSymbol? type = boundPropertyAccess.GetPublicTypeSymbol(); bool isImplicit = boundPropertyAccess.WasCompilerGenerated; return new PropertyReferenceOperation(property, arguments, instance, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) { PropertySymbol property = boundIndexerAccess.Indexer; SyntaxNode syntax = boundIndexerAccess.Syntax; ITypeSymbol? type = boundIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundIndexerAccess.WasCompilerGenerated; if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundIndexerAccess, isObjectOrCollectionInitializer: false); IOperation? instance = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, instance, _semanticModel, syntax, type, isImplicit); } private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) { IEventSymbol @event = boundEventAccess.EventSymbol.GetPublicSymbol(); IOperation? instance = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); SyntaxNode syntax = boundEventAccess.Syntax; ITypeSymbol? type = boundEventAccess.GetPublicTypeSymbol(); bool isImplicit = boundEventAccess.WasCompilerGenerated; return new EventReferenceOperation(@event, instance, _semanticModel, syntax, type, isImplicit); } private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) { IOperation eventReference = CreateBoundEventAccessOperation(boundEventAssignmentOperator); IOperation handlerValue = Create(boundEventAssignmentOperator.Argument); SyntaxNode syntax = boundEventAssignmentOperator.Syntax; bool adds = boundEventAssignmentOperator.IsAddition; ITypeSymbol? type = boundEventAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundEventAssignmentOperator.WasCompilerGenerated; return new EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, syntax, type, isImplicit); } private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) { IParameterSymbol parameter = boundParameter.ParameterSymbol.GetPublicSymbol(); SyntaxNode syntax = boundParameter.Syntax; ITypeSymbol? type = boundParameter.GetPublicTypeSymbol(); bool isImplicit = boundParameter.WasCompilerGenerated; return new ParameterReferenceOperation(parameter, _semanticModel, syntax, type, isImplicit); } internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) { SyntaxNode syntax = boundLiteral.Syntax; ITypeSymbol? type = boundLiteral.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLiteral.ConstantValue; bool isImplicit = boundLiteral.WasCompilerGenerated || @implicit; return new LiteralOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) { SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; ITypeSymbol? type = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); Debug.Assert(type is not null); bool isImplicit = boundAnonymousObjectCreationExpression.WasCompilerGenerated; ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) { MethodSymbol constructor = boundObjectCreationExpression.Constructor; SyntaxNode syntax = boundObjectCreationExpression.Syntax; ITypeSymbol? type = boundObjectCreationExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundObjectCreationExpression.ConstantValue; bool isImplicit = boundObjectCreationExpression.WasCompilerGenerated; if (boundObjectCreationExpression.ResultKind == LookupResultKind.OverloadResolutionFailure || constructor == null || constructor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } else if (boundObjectCreationExpression.Type.IsAnonymousType) { // Workaround for https://github.com/dotnet/roslyn/issues/28157 Debug.Assert(isImplicit); Debug.Assert(type is not null); ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers( boundObjectCreationExpression.Arguments, declarations: ImmutableArray<BoundAnonymousPropertyDeclaration>.Empty, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundObjectCreationExpression); IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundObjectCreationExpression.InitializerExpressionOpt); return new ObjectCreationOperation(constructor.GetPublicSymbol(), initializer, arguments, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) { IOperation operand = Create(boundWithExpression.Receiver); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); MethodSymbol? constructor = boundWithExpression.CloneMethod; SyntaxNode syntax = boundWithExpression.Syntax; ITypeSymbol? type = boundWithExpression.GetPublicTypeSymbol(); bool isImplicit = boundWithExpression.WasCompilerGenerated; return new WithOperation(operand, constructor.GetPublicSymbol(), initializer, _semanticModel, syntax, type, isImplicit); } private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicObjectCreationExpression.Arguments); ImmutableArray<string> argumentNames = boundDynamicObjectCreationExpression.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicObjectCreationExpression.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; ITypeSymbol? type = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectCreationExpression.WasCompilerGenerated; return new DynamicObjectCreationOperation(initializer, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) { switch (receiver) { case BoundObjectOrCollectionValuePlaceholder implicitReceiver: return CreateBoundDynamicMemberAccessOperation(implicitReceiver, typeArgumentsOpt: ImmutableArray<TypeSymbol>.Empty, memberName: "Add", implicitReceiver.Syntax, type: null, isImplicit: true); case BoundMethodGroup methodGroup: return CreateBoundDynamicMemberAccessOperation(methodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(methodGroup.TypeArgumentsOpt), methodGroup.Name, methodGroup.Syntax, methodGroup.GetPublicTypeSymbol(), methodGroup.WasCompilerGenerated); default: return Create(receiver); } } private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicInvocation.Arguments); ImmutableArray<string> argumentNames = boundDynamicInvocation.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicInvocation.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicInvocation.Syntax; ITypeSymbol? type = boundDynamicInvocation.GetPublicTypeSymbol(); bool isImplicit = boundDynamicInvocation.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicIndexerAccess: return Create(boundDynamicIndexerAccess.Receiver); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } internal ImmutableArray<IOperation> CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicAccess: return CreateFromArray<BoundExpression, IOperation>(boundDynamicAccess.Arguments); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateFromArray<BoundExpression, IOperation>(boundObjectInitializerMember.Arguments); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) { IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); ImmutableArray<string> argumentNames = boundDynamicIndexerAccess.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicIndexerAccess.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; ITypeSymbol? type = boundDynamicIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundDynamicIndexerAccess.WasCompilerGenerated; return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); SyntaxNode syntax = boundObjectInitializerExpression.Syntax; ITypeSymbol? type = boundObjectInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; ITypeSymbol? type = boundCollectionInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundCollectionInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) { Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; SyntaxNode syntax = boundObjectInitializerMember.Syntax; ITypeSymbol? type = boundObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerMember.WasCompilerGenerated; if ((object?)memberSymbol == null) { Debug.Assert(boundObjectInitializerMember.Type.IsDynamic()); IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); ImmutableArray<string> argumentNames = boundObjectInitializerMember.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundObjectInitializerMember.ArgumentRefKindsOpt.NullToEmpty(); return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } switch (memberSymbol.Kind) { case SymbolKind.Field: var field = (FieldSymbol)memberSymbol; bool isDeclaration = false; return new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration, createReceiver(), _semanticModel, syntax, type, constantValue: null, isImplicit); case SymbolKind.Event: var eventSymbol = (EventSymbol)memberSymbol; return new EventReferenceOperation(eventSymbol.GetPublicSymbol(), createReceiver(), _semanticModel, syntax, type, isImplicit); case SymbolKind.Property: var property = (PropertySymbol)memberSymbol; ImmutableArray<IArgumentOperation> arguments; if (!boundObjectInitializerMember.Arguments.IsEmpty) { // In nested member initializers, the property is not actually set. Instead, it is retrieved for a series of Add method calls or nested property setter calls, // so we need to use the getter for this property MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); if (accessor == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } arguments = DeriveArguments(boundObjectInitializerMember, isObjectOrCollectionInitializer); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, createReceiver(), _semanticModel, syntax, type, isImplicit); default: throw ExceptionUtilities.Unreachable; } IOperation? createReceiver() => memberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); } private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) { IOperation instanceReceiver = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); string memberName = boundDynamicObjectInitializerMember.MemberName; ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; ITypeSymbol containingType = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; ITypeSymbol? type = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectInitializerMember.WasCompilerGenerated; return new DynamicMemberReferenceOperation(instanceReceiver, memberName, typeArguments, containingType, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) { MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; IOperation? receiver = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCollectionElementInitializer); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCollectionElementInitializer.ConstantValue; bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; if (IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); return new InvocationOperation(addMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) { return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation( BoundExpression? receiver, ImmutableArray<TypeSymbol> typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) { ITypeSymbol? containingType = null; if (receiver?.Kind == BoundKind.TypeExpression) { containingType = receiver.GetPublicTypeSymbol(); receiver = null; } ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; if (!typeArgumentsOpt.IsDefault) { typeArguments = typeArgumentsOpt.GetPublicSymbols(); } IOperation? instance = Create(receiver); return new DynamicMemberReferenceOperation(instance, memberName, typeArguments, containingType, _semanticModel, syntaxNode, type, isImplicit); } private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundCollectionElementInitializer.Arguments); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames: ImmutableArray<string>.Empty, argumentRefKinds: ImmutableArray<RefKind>.Empty, _semanticModel, syntax, type, isImplicit); } private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) { // We want to ensure that we never see the UnboundLambda node, and that we don't end up having two different IOperation // nodes for the lambda expression. So, we ask the semantic model for the IOperation node for the unbound lambda syntax. // We are counting on the fact that will do the error recovery and actually create the BoundLambda node appropriate for // this syntax node. BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); return Create(boundLambda); } private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) { IMethodSymbol symbol = boundLambda.Symbol.GetPublicSymbol(); IBlockOperation body = (IBlockOperation)Create(boundLambda.Body); SyntaxNode syntax = boundLambda.Syntax; bool isImplicit = boundLambda.WasCompilerGenerated; return new AnonymousFunctionOperation(symbol, body, _semanticModel, syntax, isImplicit); } private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) { IBlockOperation? body = (IBlockOperation?)Create(boundLocalFunctionStatement.Body); IBlockOperation? ignoredBody = boundLocalFunctionStatement is { BlockBody: { }, ExpressionBody: { } exprBody } ? (IBlockOperation?)Create(exprBody) : null; IMethodSymbol symbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); SyntaxNode syntax = boundLocalFunctionStatement.Syntax; bool isImplicit = boundLocalFunctionStatement.WasCompilerGenerated; return new LocalFunctionOperation(symbol, body, ignoredBody, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) { Debug.Assert(!forceOperandImplicitLiteral || boundConversion.Operand is BoundLiteral); bool isImplicit = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; BoundExpression boundOperand = boundConversion.Operand; if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { // https://github.com/dotnet/roslyn/issues/54505 Support interpolation handlers in conversions Debug.Assert(!forceOperandImplicitLiteral); Debug.Assert(boundOperand is BoundInterpolatedString { InterpolationData: not null } or BoundBinaryOperator { InterpolatedStringHandlerData: not null }); var interpolatedString = Create(boundOperand); return new NoneOperation(ImmutableArray.Create(interpolatedString), _semanticModel, boundConversion.Syntax, boundConversion.GetPublicTypeSymbol(), boundConversion.ConstantValue, isImplicit); } if (boundConversion.ConversionKind == CSharp.ConversionKind.MethodGroup) { SyntaxNode syntax = boundConversion.Syntax; ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); Debug.Assert(!forceOperandImplicitLiteral); if (boundConversion.Type is FunctionPointerTypeSymbol) { Debug.Assert(boundConversion.SymbolOpt is object); return new AddressOfOperation( CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, type, boundConversion.WasCompilerGenerated); } // We don't check HasErrors on the conversion here because if we actually have a MethodGroup conversion, // overload resolution succeeded. The resulting method could be invalid for other reasons, but we don't // hide the resolved method. IOperation target = CreateDelegateTargetOperation(boundConversion); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { SyntaxNode syntax = boundConversion.Syntax; if (syntax.IsMissing) { // If the underlying syntax IsMissing, then that means we're in case where the compiler generated a piece of syntax to fill in for // an error, such as this case: // // int i = ; // // Semantic model has a special case here that we match: if the underlying syntax is missing, don't create a conversion expression, // and instead directly return the operand, which will be a BoundBadExpression. When we generate a node for the BoundBadExpression, // the resulting IOperation will also have a null Type. Debug.Assert(boundOperand.Kind == BoundKind.BadExpression || ((boundOperand as BoundLambda)?.Body.Statements.SingleOrDefault() as BoundReturnStatement)?. ExpressionOpt?.Kind == BoundKind.BadExpression); Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } BoundConversion correctedConversionNode = boundConversion; Conversion conversion = boundConversion.Conversion; if (boundOperand.Syntax == boundConversion.Syntax) { if (boundOperand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(boundOperand.Type, boundConversion.Type, TypeCompareKind.ConsiderEverything2)) { // Erase this conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } else { // Make this conversion implicit isImplicit = true; } } if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && boundOperand.Kind == BoundKind.Conversion) { var nestedConversion = (BoundConversion)boundOperand; BoundExpression nestedOperand = nestedConversion.Operand; if (nestedConversion.Syntax == nestedOperand.Syntax && nestedConversion.ExplicitCastInCode && nestedOperand.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything2)) { // Let's erase the nested conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion. // We need to use conversion information from the nested conversion because that is where the real conversion // information is stored. conversion = nestedConversion.Conversion; correctedConversionNode = nestedConversion; } } ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConversion.ConstantValue; // If this is a lambda or method group conversion to a delegate type, we return a delegate creation instead of a conversion if ((boundOperand.Kind == BoundKind.Lambda || boundOperand.Kind == BoundKind.UnboundLambda || boundOperand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) { IOperation target = CreateDelegateTargetOperation(correctedConversionNode); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { bool isTryCast = false; // Checked conversions only matter if the conversion is a Numeric conversion. Don't have true unless the conversion is actually numeric. bool isChecked = conversion.IsNumeric && boundConversion.Checked; IOperation operand = forceOperandImplicitLiteral ? CreateBoundLiteralOperation((BoundLiteral)correctedConversionNode.Operand, @implicit: true) : Create(correctedConversionNode.Operand); return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue, isImplicit); } } } private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) { IOperation operand = Create(boundAsOperator.Operand); SyntaxNode syntax = boundAsOperator.Syntax; Conversion conversion = boundAsOperator.Conversion; bool isTryCast = true; bool isChecked = false; ITypeSymbol? type = boundAsOperator.GetPublicTypeSymbol(); bool isImplicit = boundAsOperator.WasCompilerGenerated; return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) { IOperation target = CreateDelegateTargetOperation(boundDelegateCreationExpression); SyntaxNode syntax = boundDelegateCreationExpression.Syntax; ITypeSymbol? type = boundDelegateCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDelegateCreationExpression.WasCompilerGenerated; return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) { bool isVirtual = (methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls; IOperation? instance = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); SyntaxNode bindingSyntax = boundMethodGroup.Syntax; ITypeSymbol? bindingType = null; bool isImplicit = boundMethodGroup.WasCompilerGenerated; return new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), isVirtual, instance, _semanticModel, bindingSyntax, bindingType, boundMethodGroup.WasCompilerGenerated); } private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) { IOperation value = Create(boundIsOperator.Operand); ITypeSymbol? typeOperand = boundIsOperator.TargetType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundIsOperator.Syntax; ITypeSymbol? type = boundIsOperator.GetPublicTypeSymbol(); bool isNegated = false; bool isImplicit = boundIsOperator.WasCompilerGenerated; return new IsTypeOperation(value, typeOperand, isNegated, _semanticModel, syntax, type, isImplicit); } private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) { ITypeSymbol? typeOperand = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundSizeOfOperator.Syntax; ITypeSymbol? type = boundSizeOfOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundSizeOfOperator.ConstantValue; bool isImplicit = boundSizeOfOperator.WasCompilerGenerated; return new SizeOfOperation(typeOperand, _semanticModel, syntax, type, constantValue, isImplicit); } private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) { ITypeSymbol? typeOperand = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundTypeOfOperator.Syntax; ITypeSymbol? type = boundTypeOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundTypeOfOperator.WasCompilerGenerated; return new TypeOfOperation(typeOperand, _semanticModel, syntax, type, isImplicit); } private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) { ImmutableArray<IOperation> dimensionSizes = CreateFromArray<BoundExpression, IOperation>(boundArrayCreation.Bounds); IArrayInitializerOperation? arrayInitializer = (IArrayInitializerOperation?)Create(boundArrayCreation.InitializerOpt); SyntaxNode syntax = boundArrayCreation.Syntax; ITypeSymbol? type = boundArrayCreation.GetPublicTypeSymbol(); bool isImplicit = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); return new ArrayCreationOperation(dimensionSizes, arrayInitializer, _semanticModel, syntax, type, isImplicit); } private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) { ImmutableArray<IOperation> elementValues = CreateFromArray<BoundExpression, IOperation>(boundArrayInitialization.Initializers); SyntaxNode syntax = boundArrayInitialization.Syntax; bool isImplicit = boundArrayInitialization.WasCompilerGenerated; return new ArrayInitializerOperation(elementValues, _semanticModel, syntax, isImplicit); } private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) { SyntaxNode syntax = boundDefaultLiteral.Syntax; ConstantValue? constantValue = boundDefaultLiteral.ConstantValue; bool isImplicit = boundDefaultLiteral.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type: null, constantValue, isImplicit); } private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) { SyntaxNode syntax = boundDefaultExpression.Syntax; ITypeSymbol? type = boundDefaultExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundDefaultExpression.ConstantValue; bool isImplicit = boundDefaultExpression.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundBaseReference.Syntax; ITypeSymbol? type = boundBaseReference.GetPublicTypeSymbol(); bool isImplicit = boundBaseReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundThisReference.Syntax; ITypeSymbol? type = boundThisReference.GetPublicTypeSymbol(); bool isImplicit = boundThisReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { return IsMemberInitializer(boundAssignmentOperator) ? (IOperation)CreateBoundMemberInitializerOperation(boundAssignmentOperator) : CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); } private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) => boundAssignmentOperator.Right?.Kind == BoundKind.ObjectInitializerExpression || boundAssignmentOperator.Right?.Kind == BoundKind.CollectionInitializerExpression; private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(!IsMemberInitializer(boundAssignmentOperator)); IOperation target = Create(boundAssignmentOperator.Left); IOperation value = Create(boundAssignmentOperator.Right); bool isRef = boundAssignmentOperator.IsRef; SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundAssignmentOperator.ConstantValue; bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicit); } private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(IsMemberInitializer(boundAssignmentOperator)); IOperation initializedMember = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new MemberInitializerOperation(initializedMember, initializer, _semanticModel, syntax, type, isImplicit); } private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) { IOperation target = Create(boundCompoundAssignmentOperator.Left); IOperation value = Create(boundCompoundAssignmentOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); Conversion inConversion = boundCompoundAssignmentOperator.LeftConversion; Conversion outConversion = boundCompoundAssignmentOperator.FinalConversion; bool isLifted = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); bool isChecked = boundCompoundAssignmentOperator.Operator.Kind.IsChecked(); IMethodSymbol operatorMethod = boundCompoundAssignmentOperator.Operator.Method.GetPublicSymbol(); SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; ITypeSymbol? type = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundCompoundAssignmentOperator.WasCompilerGenerated; return new CompoundAssignmentOperation(inConversion, outConversion, operatorKind, isLifted, isChecked, operatorMethod, target, value, _semanticModel, syntax, type, isImplicit); } private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) { OperationKind operationKind = Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? OperationKind.Decrement : OperationKind.Increment; bool isPostfix = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); bool isLifted = boundIncrementOperator.OperatorKind.IsLifted(); bool isChecked = boundIncrementOperator.OperatorKind.IsChecked(); IOperation target = Create(boundIncrementOperator.Operand); IMethodSymbol? operatorMethod = boundIncrementOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundIncrementOperator.Syntax; ITypeSymbol? type = boundIncrementOperator.GetPublicTypeSymbol(); bool isImplicit = boundIncrementOperator.WasCompilerGenerated; return new IncrementOrDecrementOperation(isPostfix, isLifted, isChecked, target, operatorMethod, operationKind, _semanticModel, syntax, type, isImplicit); } private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) { SyntaxNode syntax = boundBadExpression.Syntax; // We match semantic model here: if the expression IsMissing, we have a null type, rather than the ErrorType of the bound node. ITypeSymbol? type = syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol(); // if child has syntax node point to same syntax node as bad expression, then this invalid expression is implicit bool isImplicit = boundBadExpression.WasCompilerGenerated || boundBadExpression.ChildBoundNodes.Any(e => e?.Syntax == boundBadExpression.Syntax); var children = CreateFromArray<BoundExpression, IOperation>(boundBadExpression.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundNewT.InitializerExpressionOpt); SyntaxNode syntax = boundNewT.Syntax; ITypeSymbol? type = boundNewT.GetPublicTypeSymbol(); bool isImplicit = boundNewT.WasCompilerGenerated; return new TypeParameterObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(creation.InitializerExpressionOpt); SyntaxNode syntax = creation.Syntax; ITypeSymbol? type = creation.GetPublicTypeSymbol(); bool isImplicit = creation.WasCompilerGenerated; return new NoPiaObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) { UnaryOperatorKind unaryOperatorKind = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); IOperation operand = Create(boundUnaryOperator.Operand); IMethodSymbol? operatorMethod = boundUnaryOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundUnaryOperator.Syntax; ITypeSymbol? type = boundUnaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundUnaryOperator.ConstantValue; bool isLifted = boundUnaryOperator.OperatorKind.IsLifted(); bool isChecked = boundUnaryOperator.OperatorKind.IsChecked(); bool isImplicit = boundUnaryOperator.WasCompilerGenerated; return new UnaryOperation(unaryOperatorKind, operand, isLifted, isChecked, operatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) { // Binary operators can be nested _many_ levels deep, and cause a stack overflow if we manually recurse. // To solve this, we use a manual stack for the left side. var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = boundBinaryOperatorBase; InterpolatedStringHandlerData? interpolatedData = (boundBinaryOperatorBase as BoundBinaryOperator)?.InterpolatedStringHandlerData; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null and not BoundBinaryOperator { InterpolatedStringHandlerData: not null }); Debug.Assert(interpolatedData == null || interpolatedData.GetValueOrDefault().PositionInfo.Length == stack.Count + 1); Debug.Assert(stack.Count > 0); IOperation? left = null; int positionInfoIndex = 0; while (stack.TryPop(out currentBinary)) { left ??= visitOperand(currentBinary.Left); IOperation right = visitOperand(currentBinary.Right); left = currentBinary switch { BoundBinaryOperator binaryOp => createBoundBinaryOperatorOperation(binaryOp, left, right), BoundUserDefinedConditionalLogicalOperator logicalOp => createBoundUserDefinedConditionalLogicalOperator(logicalOp, left, right), { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; } Debug.Assert(left is not null && stack.Count == 0); stack.Free(); return left; IOperation visitOperand(BoundExpression operand) => interpolatedData is { } data ? CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)operand, data.PositionInfo[positionInfoIndex++]) : Create(operand); IBinaryOperation createBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol? operatorMethod = boundBinaryOperator.Method.GetPublicSymbol(); IMethodSymbol? unaryOperatorMethod = null; // For dynamic logical operator MethodOpt is actually the unary true/false operator if (boundBinaryOperator.Type.IsDynamic() && (operatorKind == BinaryOperatorKind.ConditionalAnd || operatorKind == BinaryOperatorKind.ConditionalOr) && operatorMethod?.Parameters.Length == 1) { unaryOperatorMethod = operatorMethod; operatorMethod = null; } SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol operatorMethod = boundBinaryOperator.LogicalOperator.GetPublicSymbol(); IMethodSymbol unaryOperatorMethod = boundBinaryOperator.OperatorKind.Operator() == CSharp.BinaryOperatorKind.And ? boundBinaryOperator.FalseOperator.GetPublicSymbol() : boundBinaryOperator.TrueOperator.GetPublicSymbol(); SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } } private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) { IOperation left = Create(boundTupleBinaryOperator.Left); IOperation right = Create(boundTupleBinaryOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); SyntaxNode syntax = boundTupleBinaryOperator.Syntax; ITypeSymbol? type = boundTupleBinaryOperator.GetPublicTypeSymbol(); bool isImplicit = boundTupleBinaryOperator.WasCompilerGenerated; return new TupleBinaryOperation(operatorKind, left, right, _semanticModel, syntax, type, isImplicit); } private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) { IOperation condition = Create(boundConditionalOperator.Condition); IOperation whenTrue = Create(boundConditionalOperator.Consequence); IOperation whenFalse = Create(boundConditionalOperator.Alternative); bool isRef = boundConditionalOperator.IsRef; SyntaxNode syntax = boundConditionalOperator.Syntax; ITypeSymbol? type = boundConditionalOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConditionalOperator.ConstantValue; bool isImplicit = boundConditionalOperator.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) { IOperation value = Create(boundNullCoalescingOperator.LeftOperand); IOperation whenNull = Create(boundNullCoalescingOperator.RightOperand); SyntaxNode syntax = boundNullCoalescingOperator.Syntax; ITypeSymbol? type = boundNullCoalescingOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundNullCoalescingOperator.ConstantValue; bool isImplicit = boundNullCoalescingOperator.WasCompilerGenerated; Conversion valueConversion = boundNullCoalescingOperator.LeftConversion; if (valueConversion.Exists && !valueConversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } return new CoalesceOperation(value, whenNull, valueConversion, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) { IOperation target = Create(boundNode.LeftOperand); IOperation value = Create(boundNode.RightOperand); SyntaxNode syntax = boundNode.Syntax; ITypeSymbol? type = boundNode.GetPublicTypeSymbol(); bool isImplicit = boundNode.WasCompilerGenerated; return new CoalesceAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) { IOperation awaitedValue = Create(boundAwaitExpression.Expression); SyntaxNode syntax = boundAwaitExpression.Syntax; ITypeSymbol? type = boundAwaitExpression.GetPublicTypeSymbol(); bool isImplicit = boundAwaitExpression.WasCompilerGenerated; return new AwaitOperation(awaitedValue, _semanticModel, syntax, type, isImplicit); } private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) { IOperation arrayReference = Create(boundArrayAccess.Expression); ImmutableArray<IOperation> indices = CreateFromArray<BoundExpression, IOperation>(boundArrayAccess.Indices); SyntaxNode syntax = boundArrayAccess.Syntax; ITypeSymbol? type = boundArrayAccess.GetPublicTypeSymbol(); bool isImplicit = boundArrayAccess.WasCompilerGenerated; return new ArrayElementReferenceOperation(arrayReference, indices, _semanticModel, syntax, type, isImplicit); } private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) { IOperation argument = Create(boundNameOfOperator.Argument); SyntaxNode syntax = boundNameOfOperator.Syntax; ITypeSymbol? type = boundNameOfOperator.GetPublicTypeSymbol(); ConstantValue constantValue = boundNameOfOperator.ConstantValue; bool isImplicit = boundNameOfOperator.WasCompilerGenerated; return new NameOfOperation(argument, _semanticModel, syntax, type, constantValue, isImplicit); } private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) { IOperation expression = Create(boundThrowExpression.Expression); SyntaxNode syntax = boundThrowExpression.Syntax; ITypeSymbol? type = boundThrowExpression.GetPublicTypeSymbol(); bool isImplicit = boundThrowExpression.WasCompilerGenerated; return new ThrowOperation(expression, _semanticModel, syntax, type, isImplicit); } private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) { IOperation reference = Create(boundAddressOfOperator.Operand); SyntaxNode syntax = boundAddressOfOperator.Syntax; ITypeSymbol? type = boundAddressOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundAddressOfOperator.WasCompilerGenerated; return new AddressOfOperation(reference, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = boundImplicitReceiver.Syntax; ITypeSymbol? type = boundImplicitReceiver.GetPublicTypeSymbol(); bool isImplicit = boundImplicitReceiver.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) { IOperation operation = Create(boundConditionalAccess.Receiver); IOperation whenNotNull = Create(boundConditionalAccess.AccessExpression); SyntaxNode syntax = boundConditionalAccess.Syntax; ITypeSymbol? type = boundConditionalAccess.GetPublicTypeSymbol(); bool isImplicit = boundConditionalAccess.WasCompilerGenerated; return new ConditionalAccessOperation(operation, whenNotNull, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) { SyntaxNode syntax = boundConditionalReceiver.Syntax; ITypeSymbol? type = boundConditionalReceiver.GetPublicTypeSymbol(); bool isImplicit = boundConditionalReceiver.WasCompilerGenerated; return new ConditionalAccessInstanceOperation(_semanticModel, syntax, type, isImplicit); } private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) { ImmutableArray<IFieldSymbol> initializedFields = ImmutableArray.Create<IFieldSymbol>(boundFieldEqualsValue.Field.GetPublicSymbol()); IOperation value = Create(boundFieldEqualsValue.Value); SyntaxNode syntax = boundFieldEqualsValue.Syntax; bool isImplicit = boundFieldEqualsValue.WasCompilerGenerated; return new FieldInitializerOperation(initializedFields, boundFieldEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) { ImmutableArray<IPropertySymbol> initializedProperties = ImmutableArray.Create<IPropertySymbol>(boundPropertyEqualsValue.Property.GetPublicSymbol()); IOperation value = Create(boundPropertyEqualsValue.Value); SyntaxNode syntax = boundPropertyEqualsValue.Syntax; bool isImplicit = boundPropertyEqualsValue.WasCompilerGenerated; return new PropertyInitializerOperation(initializedProperties, boundPropertyEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) { IParameterSymbol parameter = boundParameterEqualsValue.Parameter.GetPublicSymbol(); IOperation value = Create(boundParameterEqualsValue.Value); SyntaxNode syntax = boundParameterEqualsValue.Syntax; bool isImplicit = boundParameterEqualsValue.WasCompilerGenerated; return new ParameterInitializerOperation(parameter, boundParameterEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) { ImmutableArray<IOperation> operations = CreateFromArray<BoundStatement, IOperation>(boundBlock.Statements); ImmutableArray<ILocalSymbol> locals = boundBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundBlock.Syntax; bool isImplicit = boundBlock.WasCompilerGenerated; return new BlockOperation(operations, locals, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) { ILabelSymbol target = boundContinueStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Continue; SyntaxNode syntax = boundContinueStatement.Syntax; bool isImplicit = boundContinueStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) { ILabelSymbol target = boundBreakStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Break; SyntaxNode syntax = boundBreakStatement.Syntax; bool isImplicit = boundBreakStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) { IOperation? returnedValue = null; SyntaxNode syntax = boundYieldBreakStatement.Syntax; bool isImplicit = boundYieldBreakStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldBreak, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) { ILabelSymbol target = boundGotoStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.GoTo; SyntaxNode syntax = boundGotoStatement.Syntax; bool isImplicit = boundGotoStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) { SyntaxNode syntax = boundNoOpStatement.Syntax; bool isImplicit = boundNoOpStatement.WasCompilerGenerated; return new EmptyOperation(_semanticModel, syntax, isImplicit); } private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) { IOperation condition = Create(boundIfStatement.Condition); IOperation whenTrue = Create(boundIfStatement.Consequence); IOperation? whenFalse = Create(boundIfStatement.AlternativeOpt); bool isRef = false; SyntaxNode syntax = boundIfStatement.Syntax; ITypeSymbol? type = null; ConstantValue? constantValue = null; bool isImplicit = boundIfStatement.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) { IOperation condition = Create(boundWhileStatement.Condition); IOperation body = Create(boundWhileStatement.Body); ImmutableArray<ILocalSymbol> locals = boundWhileStatement.Locals.GetPublicSymbols(); ILabelSymbol continueLabel = boundWhileStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundWhileStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = true; bool conditionIsUntil = false; SyntaxNode syntax = boundWhileStatement.Syntax; bool isImplicit = boundWhileStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) { IOperation condition = Create(boundDoStatement.Condition); IOperation body = Create(boundDoStatement.Body); ILabelSymbol continueLabel = boundDoStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundDoStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = false; bool conditionIsUntil = false; ImmutableArray<ILocalSymbol> locals = boundDoStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundDoStatement.Syntax; bool isImplicit = boundDoStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) { ImmutableArray<IOperation> before = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Initializer)); IOperation? condition = Create(boundForStatement.Condition); ImmutableArray<IOperation> atLoopBottom = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Increment)); IOperation body = Create(boundForStatement.Body); ImmutableArray<ILocalSymbol> locals = boundForStatement.OuterLocals.GetPublicSymbols(); ImmutableArray<ILocalSymbol> conditionLocals = boundForStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol continueLabel = boundForStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForStatement.Syntax; bool isImplicit = boundForStatement.WasCompilerGenerated; return new ForLoopOperation(before, conditionLocals, condition, atLoopBottom, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) { ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; ForEachLoopOperationInfo? info; if (enumeratorInfoOpt != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var compilation = (CSharpCompilation)_semanticModel.Compilation; var iDisposable = enumeratorInfoOpt.IsAsync ? compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : compilation.GetSpecialType(SpecialType.System_IDisposable); info = new ForEachLoopOperationInfo(enumeratorInfoOpt.ElementType.GetPublicSymbol(), enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), isAsynchronous: enumeratorInfoOpt.IsAsync, needsDispose: enumeratorInfoOpt.NeedsDisposal, knownToImplementIDisposable: enumeratorInfoOpt.NeedsDisposal ? compilation.Conversions. ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, iDisposable, ref discardedUseSiteInfo).IsImplicit : false, enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(), enumeratorInfoOpt.CurrentConversion, boundForEachStatement.ElementConversion, getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorInfo is { Method: { IsExtensionMethod: true } } getEnumeratorInfo ? Operation.SetParentOperation( DeriveArguments( getEnumeratorInfo.Method, getEnumeratorInfo.Arguments, argumentsToParametersOpt: default, getEnumeratorInfo.DefaultArguments, getEnumeratorInfo.Expanded, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), null) : default, disposeArguments: enumeratorInfoOpt.PatternDisposeInfo is object ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default); } else { info = null; } return info; } internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) { if (boundForEachStatement.DeconstructionOpt != null) { return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); } else if (boundForEachStatement.IterationErrorExpressionOpt != null) { return Create(boundForEachStatement.IterationErrorExpressionOpt); } else { Debug.Assert(boundForEachStatement.IterationVariables.Length == 1); var local = boundForEachStatement.IterationVariables[0]; // We use iteration variable type syntax as the underlying syntax node as there is no variable declarator syntax in the syntax tree. var declaratorSyntax = boundForEachStatement.IterationVariableType.Syntax; return new VariableDeclaratorOperation(local.GetPublicSymbol(), initializer: null, ignoredArguments: ImmutableArray<IOperation>.Empty, semanticModel: _semanticModel, syntax: declaratorSyntax, isImplicit: false); } } private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) { IOperation loopControlVariable = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); IOperation collection = Create(boundForEachStatement.Expression); var nextVariables = ImmutableArray<IOperation>.Empty; IOperation body = Create(boundForEachStatement.Body); ForEachLoopOperationInfo? info = GetForEachLoopOperatorInfo(boundForEachStatement); ImmutableArray<ILocalSymbol> locals = boundForEachStatement.IterationVariables.GetPublicSymbols(); ILabelSymbol continueLabel = boundForEachStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForEachStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForEachStatement.Syntax; bool isImplicit = boundForEachStatement.WasCompilerGenerated; bool isAsynchronous = boundForEachStatement.AwaitOpt != null; return new ForEachLoopOperation(loopControlVariable, collection, nextVariables, info, isAsynchronous, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) { var body = (IBlockOperation)Create(boundTryStatement.TryBlock); ImmutableArray<ICatchClauseOperation> catches = CreateFromArray<BoundCatchBlock, ICatchClauseOperation>(boundTryStatement.CatchBlocks); var @finally = (IBlockOperation?)Create(boundTryStatement.FinallyBlockOpt); SyntaxNode syntax = boundTryStatement.Syntax; bool isImplicit = boundTryStatement.WasCompilerGenerated; return new TryOperation(body, catches, @finally, exitLabel: null, _semanticModel, syntax, isImplicit); } private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) { IOperation? exceptionDeclarationOrExpression = CreateVariableDeclarator((BoundLocal?)boundCatchBlock.ExceptionSourceOpt); // The exception filter prologue is introduced during lowering, so should be null here. Debug.Assert(boundCatchBlock.ExceptionFilterPrologueOpt is null); IOperation? filter = Create(boundCatchBlock.ExceptionFilterOpt); IBlockOperation handler = (IBlockOperation)Create(boundCatchBlock.Body); ITypeSymbol exceptionType = boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol() ?? _semanticModel.Compilation.ObjectType; ImmutableArray<ILocalSymbol> locals = boundCatchBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundCatchBlock.Syntax; bool isImplicit = boundCatchBlock.WasCompilerGenerated; return new CatchClauseOperation(exceptionDeclarationOrExpression, exceptionType, locals, filter, handler, _semanticModel, syntax, isImplicit); } private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) { IVariableDeclarationGroupOperation variables = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); IOperation body = Create(boundFixedStatement.Body); ImmutableArray<ILocalSymbol> locals = boundFixedStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundFixedStatement.Syntax; bool isImplicit = boundFixedStatement.WasCompilerGenerated; return new FixedOperation(locals, variables, body, _semanticModel, syntax, isImplicit); } private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) { Debug.Assert((boundUsingStatement.DeclarationsOpt == null) != (boundUsingStatement.ExpressionOpt == null)); Debug.Assert(boundUsingStatement.ExpressionOpt is object || boundUsingStatement.Locals.Length > 0); IOperation resources = Create(boundUsingStatement.DeclarationsOpt ?? (BoundNode)boundUsingStatement.ExpressionOpt!); IOperation body = Create(boundUsingStatement.Body); ImmutableArray<ILocalSymbol> locals = boundUsingStatement.Locals.GetPublicSymbols(); bool isAsynchronous = boundUsingStatement.AwaitOpt != null; DisposeOperationInfo disposeOperationInfo = boundUsingStatement.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default; SyntaxNode syntax = boundUsingStatement.Syntax; bool isImplicit = boundUsingStatement.WasCompilerGenerated; return new UsingOperation(resources, body, locals, isAsynchronous, disposeOperationInfo, _semanticModel, syntax, isImplicit); } private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) { IOperation? thrownObject = Create(boundThrowStatement.ExpressionOpt); SyntaxNode syntax = boundThrowStatement.Syntax; ITypeSymbol? statementType = null; bool isImplicit = boundThrowStatement.WasCompilerGenerated; return new ThrowOperation(thrownObject, _semanticModel, syntax, statementType, isImplicit); } private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) { IOperation? returnedValue = Create(boundReturnStatement.ExpressionOpt); SyntaxNode syntax = boundReturnStatement.Syntax; bool isImplicit = boundReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.Return, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) { IOperation returnedValue = Create(boundYieldReturnStatement.Expression); SyntaxNode syntax = boundYieldReturnStatement.Syntax; bool isImplicit = boundYieldReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldReturn, _semanticModel, syntax, isImplicit); } private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) { // If there is no Enter2 method, then there will be no lock taken reference bool legacyMode = _semanticModel.Compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2) == null; ILocalSymbol? lockTakenSymbol = legacyMode ? null : new SynthesizedLocal((_semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart) as IMethodSymbol).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)_semanticModel.Compilation).GetSpecialType(SpecialType.System_Boolean)), SynthesizedLocalKind.LockTaken, syntaxOpt: boundLockStatement.Argument.Syntax).GetPublicSymbol(); IOperation lockedValue = Create(boundLockStatement.Argument); IOperation body = Create(boundLockStatement.Body); SyntaxNode syntax = boundLockStatement.Syntax; bool isImplicit = boundLockStatement.WasCompilerGenerated; return new LockOperation(lockedValue, body, lockTakenSymbol, _semanticModel, syntax, isImplicit); } private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) { SyntaxNode syntax = boundBadStatement.Syntax; // if child has syntax node point to same syntax node as bad statement, then this invalid statement is implicit bool isImplicit = boundBadStatement.WasCompilerGenerated || boundBadStatement.ChildBoundNodes.Any(e => e?.Syntax == boundBadStatement.Syntax); var children = CreateFromArray<BoundNode, IOperation>(boundBadStatement.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type: null, constantValue: null, isImplicit); } private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) { var node = boundLocalDeclaration.Syntax; var kind = node.Kind(); SyntaxNode varStatement; SyntaxNode varDeclaration; switch (kind) { case SyntaxKind.LocalDeclarationStatement: { var statement = (LocalDeclarationStatementSyntax)node; // this happen for simple int i = 0; // var statement points to LocalDeclarationStatementSyntax varStatement = statement; varDeclaration = statement.Declaration; break; } case SyntaxKind.VariableDeclarator: { // this happen for 'for loop' initializer // We generate a DeclarationGroup for this scenario to maintain tree shape consistency across IOperation. // var statement points to VariableDeclarationSyntax Debug.Assert(node.Parent != null); varStatement = node.Parent; varDeclaration = node.Parent; break; } default: { Debug.Fail($"Unexpected syntax: {kind}"); // otherwise, they points to whatever bound nodes are pointing to. varStatement = varDeclaration = node; break; } } bool multiVariableImplicit = boundLocalDeclaration.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundLocalDeclaration, varDeclaration); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundLocalDeclaration, varDeclaration); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, varDeclaration, multiVariableImplicit); // In the case of a for loop, varStatement and varDeclaration will be the same syntax node. // We can only have one explicit operation, so make sure this node is implicit in that scenario. bool isImplicit = (varStatement == varDeclaration) || boundLocalDeclaration.WasCompilerGenerated; return new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, varStatement, isImplicit); } private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) { // The syntax for the boundMultipleLocalDeclarations can either be a LocalDeclarationStatement or a VariableDeclaration, depending on the context // (using/fixed statements vs variable declaration) // We generate a DeclarationGroup for these scenarios (using/fixed) to maintain tree shape consistency across IOperation. SyntaxNode declarationGroupSyntax = boundMultipleLocalDeclarations.Syntax; SyntaxNode declarationSyntax = declarationGroupSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)declarationGroupSyntax).Declaration : declarationGroupSyntax; bool declarationIsImplicit = boundMultipleLocalDeclarations.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundMultipleLocalDeclarations, declarationSyntax); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundMultipleLocalDeclarations, declarationSyntax); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, declarationSyntax, declarationIsImplicit); // If the syntax was the same, we're in a fixed statement or using statement. We make the Group operation implicit in this scenario, as the // syntax itself is a VariableDeclaration. We do this for using declarations as well, but since that doesn't have a separate parent bound // node, we need to check the current node for that explicitly. bool isImplicit = declarationGroupSyntax == declarationSyntax || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; var variableDeclaration = new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, declarationGroupSyntax, isImplicit); if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations usingDecl) { return new UsingDeclarationOperation( variableDeclaration, isAsynchronous: usingDecl.AwaitOpt is object, disposeInfo: usingDecl.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: usingDecl.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(usingDecl.PatternDisposeInfoOpt, usingDecl.Syntax)) : default, _semanticModel, declarationGroupSyntax, isImplicit: boundMultipleLocalDeclarations.WasCompilerGenerated); } return variableDeclaration; } private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) { ILabelSymbol label = boundLabelStatement.Label.GetPublicSymbol(); SyntaxNode syntax = boundLabelStatement.Syntax; bool isImplicit = boundLabelStatement.WasCompilerGenerated; return new LabeledOperation(label, operation: null, _semanticModel, syntax, isImplicit); } private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) { ILabelSymbol label = boundLabeledStatement.Label.GetPublicSymbol(); IOperation labeledStatement = Create(boundLabeledStatement.Body); SyntaxNode syntax = boundLabeledStatement.Syntax; bool isImplicit = boundLabeledStatement.WasCompilerGenerated; return new LabeledOperation(label, labeledStatement, _semanticModel, syntax, isImplicit); } private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) { // lambda body can point to expression directly and binder can insert expression statement there. and end up statement pointing to // expression syntax node since there is no statement syntax node to point to. this will mark such one as implicit since it doesn't // actually exist in code bool isImplicit = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; SyntaxNode syntax = boundExpressionStatement.Syntax; // If we're creating the tree for a speculatively-bound constructor initializer, there can be a bound sequence as the child node here // that corresponds to the lifetime of any declared variables. IOperation expression = Create(boundExpressionStatement.Expression); if (boundExpressionStatement.Expression is BoundSequence sequence) { Debug.Assert(boundExpressionStatement.Syntax == sequence.Value.Syntax); isImplicit = true; } return new ExpressionStatementOperation(expression, _semanticModel, syntax, isImplicit); } internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) { SyntaxNode syntax = boundTupleExpression.Syntax; bool isImplicit = boundTupleExpression.WasCompilerGenerated; ITypeSymbol? type = boundTupleExpression.GetPublicTypeSymbol(); if (syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { var tupleOperation = CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false); return new DeclarationExpressionOperation(tupleOperation, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } TypeSymbol? naturalType = boundTupleExpression switch { BoundTupleLiteral { Type: var t } => t, BoundConvertedTupleLiteral { SourceTuple: { Type: var t } } => t, BoundConvertedTupleLiteral => null, { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; ImmutableArray<IOperation> elements = CreateFromArray<BoundExpression, IOperation>(boundTupleExpression.Arguments); return new TupleOperation(elements, naturalType.GetPublicSymbol(), _semanticModel, syntax, type, isImplicit); } private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo = null) { Debug.Assert(positionInfo == null || boundInterpolatedString.InterpolationData == null); ImmutableArray<IInterpolatedStringContentOperation> parts = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, positionInfo ?? boundInterpolatedString.InterpolationData?.PositionInfo[0]); SyntaxNode syntax = boundInterpolatedString.Syntax; ITypeSymbol? type = boundInterpolatedString.GetPublicTypeSymbol(); ConstantValue? constantValue = boundInterpolatedString.ConstantValue; bool isImplicit = boundInterpolatedString.WasCompilerGenerated; return new InterpolatedStringOperation(parts, _semanticModel, syntax, type, constantValue, isImplicit); } internal ImmutableArray<IInterpolatedStringContentOperation> CreateBoundInterpolatedStringContentOperation(ImmutableArray<BoundExpression> parts, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo) { return positionInfo is { } info ? createHandlerInterpolatedStringContent(info) : createNonHandlerInterpolatedStringContent(); ImmutableArray<IInterpolatedStringContentOperation> createNonHandlerInterpolatedStringContent() { var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); foreach (var part in parts) { if (part.Kind == BoundKind.StringInsert) { builder.Add((IInterpolatedStringContentOperation)Create(part)); } else { builder.Add(CreateBoundInterpolatedStringTextOperation((BoundLiteral)part)); } } return builder.ToImmutableAndFree(); } ImmutableArray<IInterpolatedStringContentOperation> createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> positionInfo) { // For interpolated string handlers, we want to deconstruct the `AppendLiteral`/`AppendFormatted` calls into // their relevant components. // https://github.com/dotnet/roslyn/issues/54505 we need to handle interpolated strings used as handler conversions. Debug.Assert(parts.Length == positionInfo.Length); var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); for (int i = 0; i < parts.Length; i++) { var part = parts[i]; var currentPosition = positionInfo[i]; BoundExpression value; BoundExpression? alignment; BoundExpression? format; switch (part) { case BoundCall call: (value, alignment, format) = getCallInfo(call.Arguments, call.ArgumentNamesOpt, currentPosition); break; case BoundDynamicInvocation dynamicInvocation: (value, alignment, format) = getCallInfo(dynamicInvocation.Arguments, dynamicInvocation.ArgumentNamesOpt, currentPosition); break; case BoundBadExpression bad: Debug.Assert(bad.ChildBoundNodes.Length == 2 + // initial value + receiver is added to the end (currentPosition.HasAlignment ? 1 : 0) + (currentPosition.HasFormat ? 1 : 0)); value = bad.ChildBoundNodes[0]; if (currentPosition.IsLiteral) { alignment = format = null; } else { alignment = currentPosition.HasAlignment ? bad.ChildBoundNodes[1] : null; format = currentPosition.HasFormat ? bad.ChildBoundNodes[^2] : null; } break; default: throw ExceptionUtilities.UnexpectedValue(part.Kind); } // We are intentionally not checking the part for implicitness here. The part is a generated AppendLiteral or AppendFormatted call, // and will always be marked as CompilerGenerated. However, our existing behavior for non-builder interpolated strings does not mark // the BoundLiteral or BoundStringInsert components as compiler generated. This generates a non-implicit IInterpolatedStringTextOperation // with an implicit literal underneath, and a non-implicit IInterpolationOperation with non-implicit underlying components. bool isImplicit = false; if (currentPosition.IsLiteral) { Debug.Assert(alignment is null); Debug.Assert(format is null); IOperation valueOperation = value switch { BoundLiteral l => CreateBoundLiteralOperation(l, @implicit: true), BoundConversion { Operand: BoundLiteral } c => CreateBoundConversionOperation(c, forceOperandImplicitLiteral: true), _ => throw ExceptionUtilities.UnexpectedValue(value.Kind), }; Debug.Assert(valueOperation.IsImplicit); builder.Add(new InterpolatedStringTextOperation(valueOperation, _semanticModel, part.Syntax, isImplicit)); } else { IOperation valueOperation = Create(value); IOperation? alignmentOperation = Create(alignment); IOperation? formatOperation = Create(format); Debug.Assert(valueOperation.Syntax != part.Syntax); builder.Add(new InterpolationOperation(valueOperation, alignmentOperation, formatOperation, _semanticModel, part.Syntax, isImplicit)); } } return builder.ToImmutableAndFree(); static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) { BoundExpression value = arguments[0]; if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) { // There was no alignment/format component, as binding will qualify those parameters by name return (value, null, null); } else { var alignmentIndex = argumentNamesOpt.IndexOf("alignment"); BoundExpression? alignment = alignmentIndex == -1 ? null : arguments[alignmentIndex]; var formatIndex = argumentNamesOpt.IndexOf("format"); BoundExpression? format = formatIndex == -1 ? null : arguments[formatIndex]; return (value, alignment, format); } } } } private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) { IOperation expression = Create(boundStringInsert.Value); IOperation? alignment = Create(boundStringInsert.Alignment); IOperation? formatString = Create(boundStringInsert.Format); SyntaxNode syntax = boundStringInsert.Syntax; bool isImplicit = boundStringInsert.WasCompilerGenerated; return new InterpolationOperation(expression, alignment, formatString, _semanticModel, syntax, isImplicit); } private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) { IOperation text = CreateBoundLiteralOperation(boundNode, @implicit: true); SyntaxNode syntax = boundNode.Syntax; bool isImplicit = boundNode.WasCompilerGenerated; return new InterpolatedStringTextOperation(text, _semanticModel, syntax, isImplicit); } private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) { IOperation value = Create(boundConstantPattern.Value); SyntaxNode syntax = boundConstantPattern.Syntax; bool isImplicit = boundConstantPattern.WasCompilerGenerated; TypeSymbol inputType = boundConstantPattern.InputType; TypeSymbol narrowedType = boundConstantPattern.NarrowedType; return new ConstantPatternOperation(value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); IOperation value = Create(boundRelationalPattern.Value); SyntaxNode syntax = boundRelationalPattern.Syntax; bool isImplicit = boundRelationalPattern.WasCompilerGenerated; TypeSymbol inputType = boundRelationalPattern.InputType; TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; return new RelationalPatternOperation(operatorKind, value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) { ISymbol? variable = boundDeclarationPattern.Variable.GetPublicSymbol(); if (variable == null && boundDeclarationPattern.VariableAccess?.Kind == BoundKind.DiscardExpression) { variable = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); } ITypeSymbol inputType = boundDeclarationPattern.InputType.GetPublicSymbol(); ITypeSymbol narrowedType = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); bool acceptsNull = boundDeclarationPattern.IsVar; ITypeSymbol? matchedType = acceptsNull ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol(); SyntaxNode syntax = boundDeclarationPattern.Syntax; bool isImplicit = boundDeclarationPattern.WasCompilerGenerated; return new DeclarationPatternOperation(matchedType, acceptsNull, variable, inputType, narrowedType, _semanticModel, syntax, isImplicit); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) { ITypeSymbol matchedType = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundRecursivePattern.Deconstruction is { IsDefault: false } deconstructions ? deconstructions.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; ImmutableArray<IPropertySubpatternOperation> propertySubpatterns = boundRecursivePattern.Properties is { IsDefault: false } properties ? properties.SelectAsArray((p, arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType), (Fac: this, MatchedType: matchedType)) : ImmutableArray<IPropertySubpatternOperation>.Empty; return new RecursivePatternOperation( matchedType, boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, isImplicit: boundRecursivePattern.WasCompilerGenerated); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) { ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundITuplePattern.Subpatterns is { IsDefault: false } subpatterns ? subpatterns.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; return new RecursivePatternOperation( boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns: ImmutableArray<IPropertySubpatternOperation>.Empty, declaredSymbol: null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, isImplicit: boundITuplePattern.WasCompilerGenerated); } private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) { return new TypePatternOperation( matchedType: boundTypePattern.NarrowedType.GetPublicSymbol(), inputType: boundTypePattern.InputType.GetPublicSymbol(), narrowedType: boundTypePattern.NarrowedType.GetPublicSymbol(), semanticModel: _semanticModel, syntax: boundTypePattern.Syntax, isImplicit: boundTypePattern.WasCompilerGenerated); } private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) { return new NegatedPatternOperation( (IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, isImplicit: boundNegatedPattern.WasCompilerGenerated); } private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) { return new BinaryPatternOperation( boundBinaryPattern.Disjunction ? BinaryOperatorKind.Or : BinaryOperatorKind.And, (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, isImplicit: boundBinaryPattern.WasCompilerGenerated); } private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) { IOperation value = Create(boundSwitchStatement.Expression); ImmutableArray<ISwitchCaseOperation> cases = CreateFromArray<BoundSwitchSection, ISwitchCaseOperation>(boundSwitchStatement.SwitchSections); ImmutableArray<ILocalSymbol> locals = boundSwitchStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol exitLabel = boundSwitchStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundSwitchStatement.Syntax; bool isImplicit = boundSwitchStatement.WasCompilerGenerated; return new SwitchOperation(locals, value, cases, exitLabel, _semanticModel, syntax, isImplicit); } private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) { ImmutableArray<ICaseClauseOperation> clauses = CreateFromArray<BoundSwitchLabel, ICaseClauseOperation>(boundSwitchSection.SwitchLabels); ImmutableArray<IOperation> body = CreateFromArray<BoundStatement, IOperation>(boundSwitchSection.Statements); ImmutableArray<ILocalSymbol> locals = boundSwitchSection.Locals.GetPublicSymbols(); return new SwitchCaseOperation(clauses, body, locals, condition: null, _semanticModel, boundSwitchSection.Syntax, isImplicit: boundSwitchSection.WasCompilerGenerated); } private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) { IOperation value = Create(boundSwitchExpression.Expression); ImmutableArray<ISwitchExpressionArmOperation> arms = CreateFromArray<BoundSwitchExpressionArm, ISwitchExpressionArmOperation>(boundSwitchExpression.SwitchArms); bool isExhaustive; if (boundSwitchExpression.DefaultLabel != null) { Debug.Assert(boundSwitchExpression.DefaultLabel is GeneratedLabelSymbol); isExhaustive = false; } else { isExhaustive = true; } return new SwitchExpressionOperation( value, arms, isExhaustive, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); } private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); IOperation? guard = Create(boundSwitchExpressionArm.WhenClause); IOperation value = Create(boundSwitchExpressionArm.Value); return new SwitchExpressionArmOperation( pattern, guard, value, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); } private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) { SyntaxNode syntax = boundSwitchLabel.Syntax; bool isImplicit = boundSwitchLabel.WasCompilerGenerated; LabelSymbol label = boundSwitchLabel.Label; if (boundSwitchLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel) { Debug.Assert(boundSwitchLabel.Pattern.Kind == BoundKind.DiscardPattern); return new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern cp && cp.InputType.IsValidV6SwitchGoverningType()) { return new SingleValueCaseClauseOperation(Create(cp.Value), label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchLabel.Pattern); IOperation? guard = Create(boundSwitchLabel.WhenClause); return new PatternCaseClauseOperation(label.GetPublicSymbol(), pattern, guard, _semanticModel, syntax, isImplicit); } } private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) { IOperation value = Create(boundIsPatternExpression.Expression); IPatternOperation pattern = (IPatternOperation)Create(boundIsPatternExpression.Pattern); SyntaxNode syntax = boundIsPatternExpression.Syntax; ITypeSymbol? type = boundIsPatternExpression.GetPublicTypeSymbol(); bool isImplicit = boundIsPatternExpression.WasCompilerGenerated; return new IsPatternOperation(value, pattern, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) { if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) { // Currently we have no IOperation APIs for different query clauses or continuation. return Create(boundQueryClause.Value); } IOperation operation = Create(boundQueryClause.Value); SyntaxNode syntax = boundQueryClause.Syntax; ITypeSymbol? type = boundQueryClause.GetPublicTypeSymbol(); bool isImplicit = boundQueryClause.WasCompilerGenerated; return new TranslatedQueryOperation(operation, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) { // We do not have operation nodes for the bound range variables, just it's value. return Create(boundRangeVariable.Value); } private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) { return new DiscardOperation( ((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), isImplicit: boundNode.WasCompilerGenerated); } private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) { return new UnaryOperation( UnaryOperatorKind.Hat, Create(boundIndex.Operand), isLifted: boundIndex.Type.IsNullableType(), isChecked: false, operatorMethod: null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), constantValue: null, isImplicit: boundIndex.WasCompilerGenerated); } private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) { IOperation? left = Create(boundRange.LeftOperandOpt); IOperation? right = Create(boundRange.RightOperandOpt); return new RangeOperation( left, right, isLifted: boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), isImplicit: boundRange.WasCompilerGenerated); } private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) { return new DiscardPatternOperation( inputType: boundNode.InputType.GetPublicSymbol(), narrowedType: boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) { // We treat `c is { ... .Prop: <pattern> }` as `c is { ...: { Prop: <pattern> } }` SyntaxNode subpatternSyntax = subpattern.Syntax; BoundPropertySubpatternMember? member = subpattern.Member; IPatternOperation pattern = (IPatternOperation)Create(subpattern.Pattern); if (member is null) { var reference = OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray<IOperation>.Empty, isImplicit: true); return new PropertySubpatternOperation(reference, pattern, _semanticModel, subpatternSyntax, isImplicit: false); } // Create an operation for last property access: // `{ SingleProp: <pattern operation> }` // or // `.LastProp: <pattern operation>` portion (treated as `{ LastProp: <pattern operation> }`) var nameSyntax = member.Syntax; var inputType = getInputType(member, matchedType); IPropertySubpatternOperation? result = createPropertySubpattern(member.Symbol, pattern, inputType, nameSyntax, isSingle: member.Receiver is null); while (member.Receiver is not null) { member = member.Receiver; nameSyntax = member.Syntax; ITypeSymbol previousType = inputType; inputType = getInputType(member, matchedType); // Create an operation for a preceding property access: // { PrecedingProp: <previous pattern operation> } IPatternOperation nestedPattern = new RecursivePatternOperation( matchedType: previousType, deconstructSymbol: null, deconstructionSubpatterns: ImmutableArray<IPatternOperation>.Empty, propertySubpatterns: ImmutableArray.Create(result), declaredSymbol: null, previousType, narrowedType: previousType, semanticModel: _semanticModel, nameSyntax, isImplicit: true); result = createPropertySubpattern(member.Symbol, nestedPattern, inputType, nameSyntax, isSingle: false); } return result; IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation pattern, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) { Debug.Assert(nameSyntax is not null); IOperation reference; switch (symbol) { case FieldSymbol field: { var constantValue = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); reference = new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration: false, createReceiver(), _semanticModel, nameSyntax, type: field.Type.GetPublicSymbol(), constantValue, isImplicit: false); break; } case PropertySymbol property: { reference = new PropertyReferenceOperation(property.GetPublicSymbol(), ImmutableArray<IArgumentOperation>.Empty, createReceiver(), _semanticModel, nameSyntax, type: property.Type.GetPublicSymbol(), isImplicit: false); break; } default: { // We should expose the symbol in this case somehow: // https://github.com/dotnet/roslyn/issues/33175 reference = OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray<IOperation>.Empty, isImplicit: false); break; } } var syntaxForPropertySubpattern = isSingle ? subpatternSyntax : nameSyntax; return new PropertySubpatternOperation(reference, pattern, _semanticModel, syntaxForPropertySubpattern, isImplicit: !isSingle); IOperation? createReceiver() => symbol?.IsStatic == false ? new InstanceReferenceOperation(InstanceReferenceKind.PatternInput, _semanticModel, nameSyntax!, receiverType, isImplicit: true) : null; } static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol matchedType) => member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? matchedType; } private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = placeholder.Syntax; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); bool isImplicit = placeholder.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private ImmutableArray<IArgumentOperation> CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) { // can't be an extension method for dispose Debug.Assert(!patternDisposeInfo.Method.IsStatic); if (patternDisposeInfo.Method.ParameterCount == 0) { return ImmutableArray<IArgumentOperation>.Empty; } Debug.Assert(!patternDisposeInfo.Expanded || patternDisposeInfo.Method.GetParameters().Last().OriginalDefinition.Type.IsSZArray()); var args = DeriveArguments( patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax, invokedAsExtensionMethod: false); return Operation.SetParentOperation(args, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { internal sealed partial class CSharpOperationFactory { private readonly SemanticModel _semanticModel; public CSharpOperationFactory(SemanticModel semanticModel) { _semanticModel = semanticModel; } [return: NotNullIfNotNull("boundNode")] public IOperation? Create(BoundNode? boundNode) { if (boundNode == null) { return null; } switch (boundNode.Kind) { case BoundKind.DeconstructValuePlaceholder: return CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); case BoundKind.DeconstructionAssignmentOperator: return CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); case BoundKind.Call: return CreateBoundCallOperation((BoundCall)boundNode); case BoundKind.Local: return CreateBoundLocalOperation((BoundLocal)boundNode); case BoundKind.FieldAccess: return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); case BoundKind.PropertyAccess: return CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); case BoundKind.IndexerAccess: return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); case BoundKind.EventAccess: return CreateBoundEventAccessOperation((BoundEventAccess)boundNode); case BoundKind.EventAssignmentOperator: return CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); case BoundKind.Parameter: return CreateBoundParameterOperation((BoundParameter)boundNode); case BoundKind.Literal: return CreateBoundLiteralOperation((BoundLiteral)boundNode); case BoundKind.DynamicInvocation: return CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); case BoundKind.DynamicIndexerAccess: return CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); case BoundKind.ObjectCreationExpression: return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); case BoundKind.WithExpression: return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); case BoundKind.DynamicObjectCreationExpression: return CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); case BoundKind.ObjectInitializerExpression: return CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); case BoundKind.CollectionInitializerExpression: return CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); case BoundKind.ObjectInitializerMember: return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); case BoundKind.CollectionElementInitializer: return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); case BoundKind.DynamicObjectInitializerMember: return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); case BoundKind.DynamicMemberAccess: return CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); case BoundKind.DynamicCollectionElementInitializer: return CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); case BoundKind.UnboundLambda: return CreateUnboundLambdaOperation((UnboundLambda)boundNode); case BoundKind.Lambda: return CreateBoundLambdaOperation((BoundLambda)boundNode); case BoundKind.Conversion: return CreateBoundConversionOperation((BoundConversion)boundNode); case BoundKind.AsOperator: return CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); case BoundKind.IsOperator: return CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); case BoundKind.SizeOfOperator: return CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); case BoundKind.TypeOfOperator: return CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); case BoundKind.ArrayCreation: return CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); case BoundKind.ArrayInitialization: return CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); case BoundKind.DefaultLiteral: return CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); case BoundKind.DefaultExpression: return CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); case BoundKind.BaseReference: return CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); case BoundKind.ThisReference: return CreateBoundThisReferenceOperation((BoundThisReference)boundNode); case BoundKind.AssignmentOperator: return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); case BoundKind.CompoundAssignmentOperator: return CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); case BoundKind.IncrementOperator: return CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); case BoundKind.BadExpression: return CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); case BoundKind.NewT: return CreateBoundNewTOperation((BoundNewT)boundNode); case BoundKind.NoPiaObjectCreationExpression: return CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); case BoundKind.UnaryOperator: return CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); case BoundKind.BinaryOperator: case BoundKind.UserDefinedConditionalLogicalOperator: return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); case BoundKind.TupleBinaryOperator: return CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); case BoundKind.ConditionalOperator: return CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); case BoundKind.NullCoalescingOperator: return CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); case BoundKind.AwaitExpression: return CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); case BoundKind.ArrayAccess: return CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); case BoundKind.NameOfOperator: return CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); case BoundKind.ThrowExpression: return CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); case BoundKind.AddressOfOperator: return CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); case BoundKind.ImplicitReceiver: return CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); case BoundKind.ConditionalAccess: return CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); case BoundKind.ConditionalReceiver: return CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); case BoundKind.FieldEqualsValue: return CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); case BoundKind.PropertyEqualsValue: return CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); case BoundKind.ParameterEqualsValue: return CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); case BoundKind.Block: return CreateBoundBlockOperation((BoundBlock)boundNode); case BoundKind.ContinueStatement: return CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); case BoundKind.BreakStatement: return CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); case BoundKind.YieldBreakStatement: return CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); case BoundKind.GotoStatement: return CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); case BoundKind.NoOpStatement: return CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); case BoundKind.IfStatement: return CreateBoundIfStatementOperation((BoundIfStatement)boundNode); case BoundKind.WhileStatement: return CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); case BoundKind.DoStatement: return CreateBoundDoStatementOperation((BoundDoStatement)boundNode); case BoundKind.ForStatement: return CreateBoundForStatementOperation((BoundForStatement)boundNode); case BoundKind.ForEachStatement: return CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); case BoundKind.TryStatement: return CreateBoundTryStatementOperation((BoundTryStatement)boundNode); case BoundKind.CatchBlock: return CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); case BoundKind.FixedStatement: return CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); case BoundKind.UsingStatement: return CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); case BoundKind.ThrowStatement: return CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); case BoundKind.ReturnStatement: return CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); case BoundKind.YieldReturnStatement: return CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); case BoundKind.LockStatement: return CreateBoundLockStatementOperation((BoundLockStatement)boundNode); case BoundKind.BadStatement: return CreateBoundBadStatementOperation((BoundBadStatement)boundNode); case BoundKind.LocalDeclaration: return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); case BoundKind.LabelStatement: return CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); case BoundKind.LabeledStatement: return CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); case BoundKind.ExpressionStatement: return CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return CreateBoundTupleOperation((BoundTupleExpression)boundNode); case BoundKind.UnconvertedInterpolatedString: throw ExceptionUtilities.Unreachable; case BoundKind.InterpolatedString: return CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); case BoundKind.StringInsert: return CreateBoundInterpolationOperation((BoundStringInsert)boundNode); case BoundKind.LocalFunctionStatement: return CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); case BoundKind.AnonymousObjectCreationExpression: return CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); case BoundKind.AnonymousPropertyDeclaration: throw ExceptionUtilities.Unreachable; case BoundKind.ConstantPattern: return CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); case BoundKind.DeclarationPattern: return CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); case BoundKind.RecursivePattern: return CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); case BoundKind.ITuplePattern: return CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); case BoundKind.DiscardPattern: return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); case BoundKind.BinaryPattern: return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); case BoundKind.NegatedPattern: return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); case BoundKind.RelationalPattern: return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); case BoundKind.TypePattern: return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); case BoundKind.SwitchStatement: return CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); case BoundKind.SwitchLabel: return CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); case BoundKind.IsPatternExpression: return CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); case BoundKind.QueryClause: return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); case BoundKind.DelegateCreationExpression: return CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); case BoundKind.RangeVariable: return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); case BoundKind.ConstructorMethodBody: return CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); case BoundKind.NonConstructorMethodBody: return CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); case BoundKind.DiscardExpression: return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); case BoundKind.NullCoalescingAssignmentOperator: return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); case BoundKind.FromEndIndexExpression: return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); case BoundKind.RangeExpression: return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); case BoundKind.SwitchSection: return CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); case BoundKind.UnconvertedConditionalOperator: throw ExceptionUtilities.Unreachable; case BoundKind.UnconvertedSwitchExpression: throw ExceptionUtilities.Unreachable; case BoundKind.ConvertedSwitchExpression: return CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); case BoundKind.SwitchExpressionArm: return CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); case BoundKind.ObjectOrCollectionValuePlaceholder: return CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); case BoundKind.FunctionPointerInvocation: return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); case BoundKind.UnconvertedAddressOfOperator: return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); case BoundKind.Attribute: case BoundKind.ArgList: case BoundKind.ArgListOperator: case BoundKind.ConvertedStackAllocExpression: case BoundKind.FixedLocalCollectionInitializer: case BoundKind.GlobalStatementInitializer: case BoundKind.HostObjectMemberReference: case BoundKind.MakeRefOperator: case BoundKind.MethodGroup: case BoundKind.NamespaceExpression: case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PreviousSubmissionReference: case BoundKind.RefTypeOperator: case BoundKind.RefValueOperator: case BoundKind.Sequence: case BoundKind.StackAllocArrayCreation: case BoundKind.TypeExpression: case BoundKind.TypeOrValueExpression: case BoundKind.IndexOrRangePatternIndexerAccess: ConstantValue? constantValue = (boundNode as BoundExpression)?.ConstantValue; bool isImplicit = boundNode.WasCompilerGenerated; if (!isImplicit) { switch (boundNode.Kind) { case BoundKind.FixedLocalCollectionInitializer: isImplicit = true; break; } } ImmutableArray<IOperation> children = GetIOperationChildren(boundNode); return new NoneOperation(children, _semanticModel, boundNode.Syntax, type: null, constantValue, isImplicit: isImplicit); default: // If you're hitting this because the IOperation test hook has failed, see // <roslyn-root>/docs/Compilers/IOperation Test Hook.md for instructions on how to fix. throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } public ImmutableArray<TOperation> CreateFromArray<TBoundNode, TOperation>(ImmutableArray<TBoundNode> boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation { if (boundNodes.IsDefault) { return ImmutableArray<TOperation>.Empty; } var builder = ArrayBuilder<TOperation>.GetInstance(boundNodes.Length); foreach (var node in boundNodes) { builder.AddIfNotNull((TOperation)Create(node)); } return builder.ToImmutableAndFree(); } private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) { return new MethodBodyOperation( (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) { return new ConstructorBodyOperation( boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal ImmutableArray<IOperation> GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) { var children = boundNodeWithChildren.Children; if (children.IsDefaultOrEmpty) { return ImmutableArray<IOperation>.Empty; } var builder = ArrayBuilder<IOperation>.GetInstance(children.Length); foreach (BoundNode? childNode in children) { if (childNode == null) { continue; } IOperation operation = Create(childNode); builder.Add(operation); } return builder.ToImmutableAndFree(); } internal ImmutableArray<IVariableDeclaratorOperation> CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (declarationSyntax as VariableDeclarationSyntax)?.Variables[0] ?? declarationSyntax)); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var multipleDeclaration = (BoundMultipleLocalDeclarationsBase)declaration; var builder = ArrayBuilder<IVariableDeclaratorOperation>.GetInstance(multipleDeclaration.LocalDeclarations.Length); foreach (var decl in multipleDeclaration.LocalDeclarations) { builder.Add((IVariableDeclaratorOperation)CreateVariableDeclaratorInternal(decl, decl.Syntax)); } return builder.ToImmutableAndFree(); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) { SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; ITypeSymbol? type = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructValuePlaceholder.WasCompilerGenerated; return new PlaceholderOperation(PlaceholderKind.Unspecified, _semanticModel, syntax, type, isImplicit); } private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) { IOperation target = Create(boundDeconstructionAssignmentOperator.Left); // Skip the synthetic deconstruction conversion wrapping the right operand. This is a compiler-generated conversion that we don't want to reflect // in the public API because it's an implementation detail. IOperation value = Create(boundDeconstructionAssignmentOperator.Right.Operand); SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; ITypeSymbol? type = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructionAssignmentOperator.WasCompilerGenerated; return new DeconstructionAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCallOperation(BoundCall boundCall) { MethodSymbol targetMethod = boundCall.Method; SyntaxNode syntax = boundCall.Syntax; ITypeSymbol? type = boundCall.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCall.ConstantValue; bool isImplicit = boundCall.WasCompilerGenerated; if (!boundCall.OriginalMethodsOpt.IsDefault || IsMethodInvalid(boundCall.ResultKind, targetMethod)) { ImmutableArray<IOperation> children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCall).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(targetMethod, boundCall.ReceiverOpt); IOperation? receiver = CreateReceiverOperation(boundCall.ReceiverOpt, targetMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCall); return new InvocationOperation(targetMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) { ITypeSymbol? type = boundFunctionPointerInvocation.GetPublicTypeSymbol(); SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; bool isImplicit = boundFunctionPointerInvocation.WasCompilerGenerated; ImmutableArray<IOperation> children; if (boundFunctionPointerInvocation.ResultKind != LookupResultKind.Viable) { children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } children = GetIOperationChildren(boundFunctionPointerInvocation); return new NoneOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) { return new AddressOfOperation( Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); } internal ImmutableArray<IOperation> CreateIgnoredDimensions(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { BoundTypeExpression? declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); return CreateFromArray<BoundExpression, IOperation>(declaredTypeOpt.BoundDimensionsOpt); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var declarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; ImmutableArray<BoundExpression> dimensions; if (declarations.Length > 0) { BoundTypeExpression? declaredTypeOpt = declarations[0].DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); dimensions = declaredTypeOpt.BoundDimensionsOpt; } else { dimensions = ImmutableArray<BoundExpression>.Empty; } return CreateFromArray<BoundExpression, IOperation>(dimensions); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) { ILocalSymbol local = boundLocal.LocalSymbol.GetPublicSymbol(); bool isDeclaration = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; SyntaxNode syntax = boundLocal.Syntax; ITypeSymbol? type = boundLocal.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLocal.ConstantValue; bool isImplicit = boundLocal.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation localReference = CreateBoundLocalOperation(boundLocal, createDeclaration: false); return new DeclarationExpressionOperation(localReference, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } return new LocalReferenceOperation(local, isDeclaration, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) { IFieldSymbol field = boundFieldAccess.FieldSymbol.GetPublicSymbol(); bool isDeclaration = boundFieldAccess.IsDeclaration; SyntaxNode syntax = boundFieldAccess.Syntax; ITypeSymbol? type = boundFieldAccess.GetPublicTypeSymbol(); ConstantValue? constantValue = boundFieldAccess.ConstantValue; bool isImplicit = boundFieldAccess.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation fieldAccess = CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false); return new DeclarationExpressionOperation(fieldAccess, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } IOperation? instance = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); return new FieldReferenceOperation(field, isDeclaration, instance, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) { switch (boundNode) { case BoundPropertyAccess boundPropertyAccess: return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); case BoundObjectInitializerMember boundObjectInitializerMember: return boundObjectInitializerMember.MemberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); case BoundIndexerAccess boundIndexerAccess: return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); default: throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) { IOperation? instance = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); var arguments = ImmutableArray<IArgumentOperation>.Empty; IPropertySymbol property = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); SyntaxNode syntax = boundPropertyAccess.Syntax; ITypeSymbol? type = boundPropertyAccess.GetPublicTypeSymbol(); bool isImplicit = boundPropertyAccess.WasCompilerGenerated; return new PropertyReferenceOperation(property, arguments, instance, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) { PropertySymbol property = boundIndexerAccess.Indexer; SyntaxNode syntax = boundIndexerAccess.Syntax; ITypeSymbol? type = boundIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundIndexerAccess.WasCompilerGenerated; if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundIndexerAccess, isObjectOrCollectionInitializer: false); IOperation? instance = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, instance, _semanticModel, syntax, type, isImplicit); } private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) { IEventSymbol @event = boundEventAccess.EventSymbol.GetPublicSymbol(); IOperation? instance = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); SyntaxNode syntax = boundEventAccess.Syntax; ITypeSymbol? type = boundEventAccess.GetPublicTypeSymbol(); bool isImplicit = boundEventAccess.WasCompilerGenerated; return new EventReferenceOperation(@event, instance, _semanticModel, syntax, type, isImplicit); } private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) { IOperation eventReference = CreateBoundEventAccessOperation(boundEventAssignmentOperator); IOperation handlerValue = Create(boundEventAssignmentOperator.Argument); SyntaxNode syntax = boundEventAssignmentOperator.Syntax; bool adds = boundEventAssignmentOperator.IsAddition; ITypeSymbol? type = boundEventAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundEventAssignmentOperator.WasCompilerGenerated; return new EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, syntax, type, isImplicit); } private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) { IParameterSymbol parameter = boundParameter.ParameterSymbol.GetPublicSymbol(); SyntaxNode syntax = boundParameter.Syntax; ITypeSymbol? type = boundParameter.GetPublicTypeSymbol(); bool isImplicit = boundParameter.WasCompilerGenerated; return new ParameterReferenceOperation(parameter, _semanticModel, syntax, type, isImplicit); } internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) { SyntaxNode syntax = boundLiteral.Syntax; ITypeSymbol? type = boundLiteral.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLiteral.ConstantValue; bool isImplicit = boundLiteral.WasCompilerGenerated || @implicit; return new LiteralOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) { SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; ITypeSymbol? type = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); Debug.Assert(type is not null); bool isImplicit = boundAnonymousObjectCreationExpression.WasCompilerGenerated; ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) { MethodSymbol constructor = boundObjectCreationExpression.Constructor; SyntaxNode syntax = boundObjectCreationExpression.Syntax; ITypeSymbol? type = boundObjectCreationExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundObjectCreationExpression.ConstantValue; bool isImplicit = boundObjectCreationExpression.WasCompilerGenerated; if (boundObjectCreationExpression.ResultKind == LookupResultKind.OverloadResolutionFailure || constructor == null || constructor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } else if (boundObjectCreationExpression.Type.IsAnonymousType) { // Workaround for https://github.com/dotnet/roslyn/issues/28157 Debug.Assert(isImplicit); Debug.Assert(type is not null); ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers( boundObjectCreationExpression.Arguments, declarations: ImmutableArray<BoundAnonymousPropertyDeclaration>.Empty, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundObjectCreationExpression); IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundObjectCreationExpression.InitializerExpressionOpt); return new ObjectCreationOperation(constructor.GetPublicSymbol(), initializer, arguments, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) { IOperation operand = Create(boundWithExpression.Receiver); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); MethodSymbol? constructor = boundWithExpression.CloneMethod; SyntaxNode syntax = boundWithExpression.Syntax; ITypeSymbol? type = boundWithExpression.GetPublicTypeSymbol(); bool isImplicit = boundWithExpression.WasCompilerGenerated; return new WithOperation(operand, constructor.GetPublicSymbol(), initializer, _semanticModel, syntax, type, isImplicit); } private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicObjectCreationExpression.Arguments); ImmutableArray<string> argumentNames = boundDynamicObjectCreationExpression.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicObjectCreationExpression.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; ITypeSymbol? type = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectCreationExpression.WasCompilerGenerated; return new DynamicObjectCreationOperation(initializer, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) { switch (receiver) { case BoundObjectOrCollectionValuePlaceholder implicitReceiver: return CreateBoundDynamicMemberAccessOperation(implicitReceiver, typeArgumentsOpt: ImmutableArray<TypeSymbol>.Empty, memberName: "Add", implicitReceiver.Syntax, type: null, isImplicit: true); case BoundMethodGroup methodGroup: return CreateBoundDynamicMemberAccessOperation(methodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(methodGroup.TypeArgumentsOpt), methodGroup.Name, methodGroup.Syntax, methodGroup.GetPublicTypeSymbol(), methodGroup.WasCompilerGenerated); default: return Create(receiver); } } private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicInvocation.Arguments); ImmutableArray<string> argumentNames = boundDynamicInvocation.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicInvocation.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicInvocation.Syntax; ITypeSymbol? type = boundDynamicInvocation.GetPublicTypeSymbol(); bool isImplicit = boundDynamicInvocation.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicIndexerAccess: return Create(boundDynamicIndexerAccess.Receiver); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } internal ImmutableArray<IOperation> CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicAccess: return CreateFromArray<BoundExpression, IOperation>(boundDynamicAccess.Arguments); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateFromArray<BoundExpression, IOperation>(boundObjectInitializerMember.Arguments); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) { IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); ImmutableArray<string> argumentNames = boundDynamicIndexerAccess.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicIndexerAccess.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; ITypeSymbol? type = boundDynamicIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundDynamicIndexerAccess.WasCompilerGenerated; return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); SyntaxNode syntax = boundObjectInitializerExpression.Syntax; ITypeSymbol? type = boundObjectInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; ITypeSymbol? type = boundCollectionInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundCollectionInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) { Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; SyntaxNode syntax = boundObjectInitializerMember.Syntax; ITypeSymbol? type = boundObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerMember.WasCompilerGenerated; if ((object?)memberSymbol == null) { Debug.Assert(boundObjectInitializerMember.Type.IsDynamic()); IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); ImmutableArray<string> argumentNames = boundObjectInitializerMember.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundObjectInitializerMember.ArgumentRefKindsOpt.NullToEmpty(); return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } switch (memberSymbol.Kind) { case SymbolKind.Field: var field = (FieldSymbol)memberSymbol; bool isDeclaration = false; return new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration, createReceiver(), _semanticModel, syntax, type, constantValue: null, isImplicit); case SymbolKind.Event: var eventSymbol = (EventSymbol)memberSymbol; return new EventReferenceOperation(eventSymbol.GetPublicSymbol(), createReceiver(), _semanticModel, syntax, type, isImplicit); case SymbolKind.Property: var property = (PropertySymbol)memberSymbol; ImmutableArray<IArgumentOperation> arguments; if (!boundObjectInitializerMember.Arguments.IsEmpty) { // In nested member initializers, the property is not actually set. Instead, it is retrieved for a series of Add method calls or nested property setter calls, // so we need to use the getter for this property MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); if (accessor == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } arguments = DeriveArguments(boundObjectInitializerMember, isObjectOrCollectionInitializer); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, createReceiver(), _semanticModel, syntax, type, isImplicit); default: throw ExceptionUtilities.Unreachable; } IOperation? createReceiver() => memberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); } private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) { IOperation instanceReceiver = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); string memberName = boundDynamicObjectInitializerMember.MemberName; ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; ITypeSymbol containingType = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; ITypeSymbol? type = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectInitializerMember.WasCompilerGenerated; return new DynamicMemberReferenceOperation(instanceReceiver, memberName, typeArguments, containingType, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) { MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; IOperation? receiver = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCollectionElementInitializer); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCollectionElementInitializer.ConstantValue; bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; if (IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); return new InvocationOperation(addMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) { return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation( BoundExpression? receiver, ImmutableArray<TypeSymbol> typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) { ITypeSymbol? containingType = null; if (receiver?.Kind == BoundKind.TypeExpression) { containingType = receiver.GetPublicTypeSymbol(); receiver = null; } ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; if (!typeArgumentsOpt.IsDefault) { typeArguments = typeArgumentsOpt.GetPublicSymbols(); } IOperation? instance = Create(receiver); return new DynamicMemberReferenceOperation(instance, memberName, typeArguments, containingType, _semanticModel, syntaxNode, type, isImplicit); } private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundCollectionElementInitializer.Arguments); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames: ImmutableArray<string>.Empty, argumentRefKinds: ImmutableArray<RefKind>.Empty, _semanticModel, syntax, type, isImplicit); } private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) { // We want to ensure that we never see the UnboundLambda node, and that we don't end up having two different IOperation // nodes for the lambda expression. So, we ask the semantic model for the IOperation node for the unbound lambda syntax. // We are counting on the fact that will do the error recovery and actually create the BoundLambda node appropriate for // this syntax node. BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); return Create(boundLambda); } private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) { IMethodSymbol symbol = boundLambda.Symbol.GetPublicSymbol(); IBlockOperation body = (IBlockOperation)Create(boundLambda.Body); SyntaxNode syntax = boundLambda.Syntax; bool isImplicit = boundLambda.WasCompilerGenerated; return new AnonymousFunctionOperation(symbol, body, _semanticModel, syntax, isImplicit); } private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) { IBlockOperation? body = (IBlockOperation?)Create(boundLocalFunctionStatement.Body); IBlockOperation? ignoredBody = boundLocalFunctionStatement is { BlockBody: { }, ExpressionBody: { } exprBody } ? (IBlockOperation?)Create(exprBody) : null; IMethodSymbol symbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); SyntaxNode syntax = boundLocalFunctionStatement.Syntax; bool isImplicit = boundLocalFunctionStatement.WasCompilerGenerated; return new LocalFunctionOperation(symbol, body, ignoredBody, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) { Debug.Assert(!forceOperandImplicitLiteral || boundConversion.Operand is BoundLiteral); bool isImplicit = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; BoundExpression boundOperand = boundConversion.Operand; if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { // https://github.com/dotnet/roslyn/issues/54505 Support interpolation handlers in conversions Debug.Assert(!forceOperandImplicitLiteral); Debug.Assert(boundOperand is BoundInterpolatedString { InterpolationData: not null } or BoundBinaryOperator { InterpolatedStringHandlerData: not null }); var interpolatedString = Create(boundOperand); return new NoneOperation(ImmutableArray.Create(interpolatedString), _semanticModel, boundConversion.Syntax, boundConversion.GetPublicTypeSymbol(), boundConversion.ConstantValue, isImplicit); } if (boundConversion.ConversionKind == CSharp.ConversionKind.MethodGroup) { SyntaxNode syntax = boundConversion.Syntax; ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); Debug.Assert(!forceOperandImplicitLiteral); if (boundConversion.Type is FunctionPointerTypeSymbol) { Debug.Assert(boundConversion.SymbolOpt is object); return new AddressOfOperation( CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, type, boundConversion.WasCompilerGenerated); } // We don't check HasErrors on the conversion here because if we actually have a MethodGroup conversion, // overload resolution succeeded. The resulting method could be invalid for other reasons, but we don't // hide the resolved method. IOperation target = CreateDelegateTargetOperation(boundConversion); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { SyntaxNode syntax = boundConversion.Syntax; if (syntax.IsMissing) { // If the underlying syntax IsMissing, then that means we're in case where the compiler generated a piece of syntax to fill in for // an error, such as this case: // // int i = ; // // Semantic model has a special case here that we match: if the underlying syntax is missing, don't create a conversion expression, // and instead directly return the operand, which will be a BoundBadExpression. When we generate a node for the BoundBadExpression, // the resulting IOperation will also have a null Type. Debug.Assert(boundOperand.Kind == BoundKind.BadExpression || ((boundOperand as BoundLambda)?.Body.Statements.SingleOrDefault() as BoundReturnStatement)?. ExpressionOpt?.Kind == BoundKind.BadExpression); Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } BoundConversion correctedConversionNode = boundConversion; Conversion conversion = boundConversion.Conversion; if (boundOperand.Syntax == boundConversion.Syntax) { if (boundOperand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(boundOperand.Type, boundConversion.Type, TypeCompareKind.ConsiderEverything2)) { // Erase this conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } else { // Make this conversion implicit isImplicit = true; } } if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && boundOperand.Kind == BoundKind.Conversion) { var nestedConversion = (BoundConversion)boundOperand; BoundExpression nestedOperand = nestedConversion.Operand; if (nestedConversion.Syntax == nestedOperand.Syntax && nestedConversion.ExplicitCastInCode && nestedOperand.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything2)) { // Let's erase the nested conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion. // We need to use conversion information from the nested conversion because that is where the real conversion // information is stored. conversion = nestedConversion.Conversion; correctedConversionNode = nestedConversion; } } ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConversion.ConstantValue; // If this is a lambda or method group conversion to a delegate type, we return a delegate creation instead of a conversion if ((boundOperand.Kind == BoundKind.Lambda || boundOperand.Kind == BoundKind.UnboundLambda || boundOperand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) { IOperation target = CreateDelegateTargetOperation(correctedConversionNode); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { bool isTryCast = false; // Checked conversions only matter if the conversion is a Numeric conversion. Don't have true unless the conversion is actually numeric. bool isChecked = conversion.IsNumeric && boundConversion.Checked; IOperation operand = forceOperandImplicitLiteral ? CreateBoundLiteralOperation((BoundLiteral)correctedConversionNode.Operand, @implicit: true) : Create(correctedConversionNode.Operand); return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue, isImplicit); } } } private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) { IOperation operand = Create(boundAsOperator.Operand); SyntaxNode syntax = boundAsOperator.Syntax; Conversion conversion = boundAsOperator.Conversion; bool isTryCast = true; bool isChecked = false; ITypeSymbol? type = boundAsOperator.GetPublicTypeSymbol(); bool isImplicit = boundAsOperator.WasCompilerGenerated; return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) { IOperation target = CreateDelegateTargetOperation(boundDelegateCreationExpression); SyntaxNode syntax = boundDelegateCreationExpression.Syntax; ITypeSymbol? type = boundDelegateCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDelegateCreationExpression.WasCompilerGenerated; return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) { bool isVirtual = (methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls; IOperation? instance = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); SyntaxNode bindingSyntax = boundMethodGroup.Syntax; ITypeSymbol? bindingType = null; bool isImplicit = boundMethodGroup.WasCompilerGenerated; return new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), isVirtual, instance, _semanticModel, bindingSyntax, bindingType, boundMethodGroup.WasCompilerGenerated); } private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) { IOperation value = Create(boundIsOperator.Operand); ITypeSymbol? typeOperand = boundIsOperator.TargetType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundIsOperator.Syntax; ITypeSymbol? type = boundIsOperator.GetPublicTypeSymbol(); bool isNegated = false; bool isImplicit = boundIsOperator.WasCompilerGenerated; return new IsTypeOperation(value, typeOperand, isNegated, _semanticModel, syntax, type, isImplicit); } private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) { ITypeSymbol? typeOperand = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundSizeOfOperator.Syntax; ITypeSymbol? type = boundSizeOfOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundSizeOfOperator.ConstantValue; bool isImplicit = boundSizeOfOperator.WasCompilerGenerated; return new SizeOfOperation(typeOperand, _semanticModel, syntax, type, constantValue, isImplicit); } private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) { ITypeSymbol? typeOperand = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundTypeOfOperator.Syntax; ITypeSymbol? type = boundTypeOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundTypeOfOperator.WasCompilerGenerated; return new TypeOfOperation(typeOperand, _semanticModel, syntax, type, isImplicit); } private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) { ImmutableArray<IOperation> dimensionSizes = CreateFromArray<BoundExpression, IOperation>(boundArrayCreation.Bounds); IArrayInitializerOperation? arrayInitializer = (IArrayInitializerOperation?)Create(boundArrayCreation.InitializerOpt); SyntaxNode syntax = boundArrayCreation.Syntax; ITypeSymbol? type = boundArrayCreation.GetPublicTypeSymbol(); bool isImplicit = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); return new ArrayCreationOperation(dimensionSizes, arrayInitializer, _semanticModel, syntax, type, isImplicit); } private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) { ImmutableArray<IOperation> elementValues = CreateFromArray<BoundExpression, IOperation>(boundArrayInitialization.Initializers); SyntaxNode syntax = boundArrayInitialization.Syntax; bool isImplicit = boundArrayInitialization.WasCompilerGenerated; return new ArrayInitializerOperation(elementValues, _semanticModel, syntax, isImplicit); } private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) { SyntaxNode syntax = boundDefaultLiteral.Syntax; ConstantValue? constantValue = boundDefaultLiteral.ConstantValue; bool isImplicit = boundDefaultLiteral.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type: null, constantValue, isImplicit); } private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) { SyntaxNode syntax = boundDefaultExpression.Syntax; ITypeSymbol? type = boundDefaultExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundDefaultExpression.ConstantValue; bool isImplicit = boundDefaultExpression.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundBaseReference.Syntax; ITypeSymbol? type = boundBaseReference.GetPublicTypeSymbol(); bool isImplicit = boundBaseReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundThisReference.Syntax; ITypeSymbol? type = boundThisReference.GetPublicTypeSymbol(); bool isImplicit = boundThisReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { return IsMemberInitializer(boundAssignmentOperator) ? (IOperation)CreateBoundMemberInitializerOperation(boundAssignmentOperator) : CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); } private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) => boundAssignmentOperator.Right?.Kind == BoundKind.ObjectInitializerExpression || boundAssignmentOperator.Right?.Kind == BoundKind.CollectionInitializerExpression; private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(!IsMemberInitializer(boundAssignmentOperator)); IOperation target = Create(boundAssignmentOperator.Left); IOperation value = Create(boundAssignmentOperator.Right); bool isRef = boundAssignmentOperator.IsRef; SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundAssignmentOperator.ConstantValue; bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicit); } private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(IsMemberInitializer(boundAssignmentOperator)); IOperation initializedMember = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new MemberInitializerOperation(initializedMember, initializer, _semanticModel, syntax, type, isImplicit); } private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) { IOperation target = Create(boundCompoundAssignmentOperator.Left); IOperation value = Create(boundCompoundAssignmentOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); Conversion inConversion = boundCompoundAssignmentOperator.LeftConversion; Conversion outConversion = boundCompoundAssignmentOperator.FinalConversion; bool isLifted = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); bool isChecked = boundCompoundAssignmentOperator.Operator.Kind.IsChecked(); IMethodSymbol operatorMethod = boundCompoundAssignmentOperator.Operator.Method.GetPublicSymbol(); SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; ITypeSymbol? type = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundCompoundAssignmentOperator.WasCompilerGenerated; return new CompoundAssignmentOperation(inConversion, outConversion, operatorKind, isLifted, isChecked, operatorMethod, target, value, _semanticModel, syntax, type, isImplicit); } private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) { OperationKind operationKind = Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? OperationKind.Decrement : OperationKind.Increment; bool isPostfix = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); bool isLifted = boundIncrementOperator.OperatorKind.IsLifted(); bool isChecked = boundIncrementOperator.OperatorKind.IsChecked(); IOperation target = Create(boundIncrementOperator.Operand); IMethodSymbol? operatorMethod = boundIncrementOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundIncrementOperator.Syntax; ITypeSymbol? type = boundIncrementOperator.GetPublicTypeSymbol(); bool isImplicit = boundIncrementOperator.WasCompilerGenerated; return new IncrementOrDecrementOperation(isPostfix, isLifted, isChecked, target, operatorMethod, operationKind, _semanticModel, syntax, type, isImplicit); } private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) { SyntaxNode syntax = boundBadExpression.Syntax; // We match semantic model here: if the expression IsMissing, we have a null type, rather than the ErrorType of the bound node. ITypeSymbol? type = syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol(); // if child has syntax node point to same syntax node as bad expression, then this invalid expression is implicit bool isImplicit = boundBadExpression.WasCompilerGenerated || boundBadExpression.ChildBoundNodes.Any(e => e?.Syntax == boundBadExpression.Syntax); var children = CreateFromArray<BoundExpression, IOperation>(boundBadExpression.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundNewT.InitializerExpressionOpt); SyntaxNode syntax = boundNewT.Syntax; ITypeSymbol? type = boundNewT.GetPublicTypeSymbol(); bool isImplicit = boundNewT.WasCompilerGenerated; return new TypeParameterObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(creation.InitializerExpressionOpt); SyntaxNode syntax = creation.Syntax; ITypeSymbol? type = creation.GetPublicTypeSymbol(); bool isImplicit = creation.WasCompilerGenerated; return new NoPiaObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) { UnaryOperatorKind unaryOperatorKind = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); IOperation operand = Create(boundUnaryOperator.Operand); IMethodSymbol? operatorMethod = boundUnaryOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundUnaryOperator.Syntax; ITypeSymbol? type = boundUnaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundUnaryOperator.ConstantValue; bool isLifted = boundUnaryOperator.OperatorKind.IsLifted(); bool isChecked = boundUnaryOperator.OperatorKind.IsChecked(); bool isImplicit = boundUnaryOperator.WasCompilerGenerated; return new UnaryOperation(unaryOperatorKind, operand, isLifted, isChecked, operatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) { if (boundBinaryOperatorBase is BoundBinaryOperator { InterpolatedStringHandlerData: not null } binary) { return CreateBoundInterpolatedStringBinaryOperator(binary); } // Binary operators can be nested _many_ levels deep, and cause a stack overflow if we manually recurse. // To solve this, we use a manual stack for the left side. var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = boundBinaryOperatorBase; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null and not BoundBinaryOperator { InterpolatedStringHandlerData: not null }); Debug.Assert(stack.Count > 0); IOperation? left = null; while (stack.TryPop(out currentBinary)) { left ??= Create(currentBinary.Left); IOperation right = Create(currentBinary.Right); left = currentBinary switch { BoundBinaryOperator binaryOp => CreateBoundBinaryOperatorOperation(binaryOp, left, right), BoundUserDefinedConditionalLogicalOperator logicalOp => createBoundUserDefinedConditionalLogicalOperator(logicalOp, left, right), { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; } Debug.Assert(left is not null && stack.Count == 0); stack.Free(); return left; IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol operatorMethod = boundBinaryOperator.LogicalOperator.GetPublicSymbol(); IMethodSymbol unaryOperatorMethod = boundBinaryOperator.OperatorKind.Operator() == CSharp.BinaryOperatorKind.And ? boundBinaryOperator.FalseOperator.GetPublicSymbol() : boundBinaryOperator.TrueOperator.GetPublicSymbol(); SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } } private IBinaryOperation CreateBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol? operatorMethod = boundBinaryOperator.Method.GetPublicSymbol(); IMethodSymbol? unaryOperatorMethod = null; // For dynamic logical operator MethodOpt is actually the unary true/false operator if (boundBinaryOperator.Type.IsDynamic() && (operatorKind == BinaryOperatorKind.ConditionalAnd || operatorKind == BinaryOperatorKind.ConditionalOr) && operatorMethod?.Parameters.Length == 1) { unaryOperatorMethod = operatorMethod; operatorMethod = null; } SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundInterpolatedStringBinaryOperator(BoundBinaryOperator boundBinaryOperator) { Debug.Assert(boundBinaryOperator.InterpolatedStringHandlerData is not null); Func<BoundInterpolatedString, int, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createInterpolatedString = createInterpolatedStringOperand; Func<BoundBinaryOperator, IOperation, IOperation, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createBinaryOperator = createBoundBinaryOperatorOperation; return boundBinaryOperator.RewriteInterpolatedStringAddition((this, boundBinaryOperator.InterpolatedStringHandlerData.GetValueOrDefault()), createInterpolatedString, createBinaryOperator); static IInterpolatedStringOperation createInterpolatedStringOperand( BoundInterpolatedString boundInterpolatedString, int i, (CSharpOperationFactory @this, InterpolatedStringHandlerData Data) arg) => [email protected](boundInterpolatedString, arg.Data.PositionInfo[i]); static IBinaryOperation createBoundBinaryOperatorOperation( BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right, (CSharpOperationFactory @this, InterpolatedStringHandlerData _) arg) => [email protected](boundBinaryOperator, left, right); } private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) { IOperation left = Create(boundTupleBinaryOperator.Left); IOperation right = Create(boundTupleBinaryOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); SyntaxNode syntax = boundTupleBinaryOperator.Syntax; ITypeSymbol? type = boundTupleBinaryOperator.GetPublicTypeSymbol(); bool isImplicit = boundTupleBinaryOperator.WasCompilerGenerated; return new TupleBinaryOperation(operatorKind, left, right, _semanticModel, syntax, type, isImplicit); } private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) { IOperation condition = Create(boundConditionalOperator.Condition); IOperation whenTrue = Create(boundConditionalOperator.Consequence); IOperation whenFalse = Create(boundConditionalOperator.Alternative); bool isRef = boundConditionalOperator.IsRef; SyntaxNode syntax = boundConditionalOperator.Syntax; ITypeSymbol? type = boundConditionalOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConditionalOperator.ConstantValue; bool isImplicit = boundConditionalOperator.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) { IOperation value = Create(boundNullCoalescingOperator.LeftOperand); IOperation whenNull = Create(boundNullCoalescingOperator.RightOperand); SyntaxNode syntax = boundNullCoalescingOperator.Syntax; ITypeSymbol? type = boundNullCoalescingOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundNullCoalescingOperator.ConstantValue; bool isImplicit = boundNullCoalescingOperator.WasCompilerGenerated; Conversion valueConversion = boundNullCoalescingOperator.LeftConversion; if (valueConversion.Exists && !valueConversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } return new CoalesceOperation(value, whenNull, valueConversion, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) { IOperation target = Create(boundNode.LeftOperand); IOperation value = Create(boundNode.RightOperand); SyntaxNode syntax = boundNode.Syntax; ITypeSymbol? type = boundNode.GetPublicTypeSymbol(); bool isImplicit = boundNode.WasCompilerGenerated; return new CoalesceAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) { IOperation awaitedValue = Create(boundAwaitExpression.Expression); SyntaxNode syntax = boundAwaitExpression.Syntax; ITypeSymbol? type = boundAwaitExpression.GetPublicTypeSymbol(); bool isImplicit = boundAwaitExpression.WasCompilerGenerated; return new AwaitOperation(awaitedValue, _semanticModel, syntax, type, isImplicit); } private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) { IOperation arrayReference = Create(boundArrayAccess.Expression); ImmutableArray<IOperation> indices = CreateFromArray<BoundExpression, IOperation>(boundArrayAccess.Indices); SyntaxNode syntax = boundArrayAccess.Syntax; ITypeSymbol? type = boundArrayAccess.GetPublicTypeSymbol(); bool isImplicit = boundArrayAccess.WasCompilerGenerated; return new ArrayElementReferenceOperation(arrayReference, indices, _semanticModel, syntax, type, isImplicit); } private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) { IOperation argument = Create(boundNameOfOperator.Argument); SyntaxNode syntax = boundNameOfOperator.Syntax; ITypeSymbol? type = boundNameOfOperator.GetPublicTypeSymbol(); ConstantValue constantValue = boundNameOfOperator.ConstantValue; bool isImplicit = boundNameOfOperator.WasCompilerGenerated; return new NameOfOperation(argument, _semanticModel, syntax, type, constantValue, isImplicit); } private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) { IOperation expression = Create(boundThrowExpression.Expression); SyntaxNode syntax = boundThrowExpression.Syntax; ITypeSymbol? type = boundThrowExpression.GetPublicTypeSymbol(); bool isImplicit = boundThrowExpression.WasCompilerGenerated; return new ThrowOperation(expression, _semanticModel, syntax, type, isImplicit); } private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) { IOperation reference = Create(boundAddressOfOperator.Operand); SyntaxNode syntax = boundAddressOfOperator.Syntax; ITypeSymbol? type = boundAddressOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundAddressOfOperator.WasCompilerGenerated; return new AddressOfOperation(reference, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = boundImplicitReceiver.Syntax; ITypeSymbol? type = boundImplicitReceiver.GetPublicTypeSymbol(); bool isImplicit = boundImplicitReceiver.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) { IOperation operation = Create(boundConditionalAccess.Receiver); IOperation whenNotNull = Create(boundConditionalAccess.AccessExpression); SyntaxNode syntax = boundConditionalAccess.Syntax; ITypeSymbol? type = boundConditionalAccess.GetPublicTypeSymbol(); bool isImplicit = boundConditionalAccess.WasCompilerGenerated; return new ConditionalAccessOperation(operation, whenNotNull, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) { SyntaxNode syntax = boundConditionalReceiver.Syntax; ITypeSymbol? type = boundConditionalReceiver.GetPublicTypeSymbol(); bool isImplicit = boundConditionalReceiver.WasCompilerGenerated; return new ConditionalAccessInstanceOperation(_semanticModel, syntax, type, isImplicit); } private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) { ImmutableArray<IFieldSymbol> initializedFields = ImmutableArray.Create<IFieldSymbol>(boundFieldEqualsValue.Field.GetPublicSymbol()); IOperation value = Create(boundFieldEqualsValue.Value); SyntaxNode syntax = boundFieldEqualsValue.Syntax; bool isImplicit = boundFieldEqualsValue.WasCompilerGenerated; return new FieldInitializerOperation(initializedFields, boundFieldEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) { ImmutableArray<IPropertySymbol> initializedProperties = ImmutableArray.Create<IPropertySymbol>(boundPropertyEqualsValue.Property.GetPublicSymbol()); IOperation value = Create(boundPropertyEqualsValue.Value); SyntaxNode syntax = boundPropertyEqualsValue.Syntax; bool isImplicit = boundPropertyEqualsValue.WasCompilerGenerated; return new PropertyInitializerOperation(initializedProperties, boundPropertyEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) { IParameterSymbol parameter = boundParameterEqualsValue.Parameter.GetPublicSymbol(); IOperation value = Create(boundParameterEqualsValue.Value); SyntaxNode syntax = boundParameterEqualsValue.Syntax; bool isImplicit = boundParameterEqualsValue.WasCompilerGenerated; return new ParameterInitializerOperation(parameter, boundParameterEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) { ImmutableArray<IOperation> operations = CreateFromArray<BoundStatement, IOperation>(boundBlock.Statements); ImmutableArray<ILocalSymbol> locals = boundBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundBlock.Syntax; bool isImplicit = boundBlock.WasCompilerGenerated; return new BlockOperation(operations, locals, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) { ILabelSymbol target = boundContinueStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Continue; SyntaxNode syntax = boundContinueStatement.Syntax; bool isImplicit = boundContinueStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) { ILabelSymbol target = boundBreakStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Break; SyntaxNode syntax = boundBreakStatement.Syntax; bool isImplicit = boundBreakStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) { IOperation? returnedValue = null; SyntaxNode syntax = boundYieldBreakStatement.Syntax; bool isImplicit = boundYieldBreakStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldBreak, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) { ILabelSymbol target = boundGotoStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.GoTo; SyntaxNode syntax = boundGotoStatement.Syntax; bool isImplicit = boundGotoStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) { SyntaxNode syntax = boundNoOpStatement.Syntax; bool isImplicit = boundNoOpStatement.WasCompilerGenerated; return new EmptyOperation(_semanticModel, syntax, isImplicit); } private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) { IOperation condition = Create(boundIfStatement.Condition); IOperation whenTrue = Create(boundIfStatement.Consequence); IOperation? whenFalse = Create(boundIfStatement.AlternativeOpt); bool isRef = false; SyntaxNode syntax = boundIfStatement.Syntax; ITypeSymbol? type = null; ConstantValue? constantValue = null; bool isImplicit = boundIfStatement.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) { IOperation condition = Create(boundWhileStatement.Condition); IOperation body = Create(boundWhileStatement.Body); ImmutableArray<ILocalSymbol> locals = boundWhileStatement.Locals.GetPublicSymbols(); ILabelSymbol continueLabel = boundWhileStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundWhileStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = true; bool conditionIsUntil = false; SyntaxNode syntax = boundWhileStatement.Syntax; bool isImplicit = boundWhileStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) { IOperation condition = Create(boundDoStatement.Condition); IOperation body = Create(boundDoStatement.Body); ILabelSymbol continueLabel = boundDoStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundDoStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = false; bool conditionIsUntil = false; ImmutableArray<ILocalSymbol> locals = boundDoStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundDoStatement.Syntax; bool isImplicit = boundDoStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) { ImmutableArray<IOperation> before = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Initializer)); IOperation? condition = Create(boundForStatement.Condition); ImmutableArray<IOperation> atLoopBottom = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Increment)); IOperation body = Create(boundForStatement.Body); ImmutableArray<ILocalSymbol> locals = boundForStatement.OuterLocals.GetPublicSymbols(); ImmutableArray<ILocalSymbol> conditionLocals = boundForStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol continueLabel = boundForStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForStatement.Syntax; bool isImplicit = boundForStatement.WasCompilerGenerated; return new ForLoopOperation(before, conditionLocals, condition, atLoopBottom, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) { ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; ForEachLoopOperationInfo? info; if (enumeratorInfoOpt != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var compilation = (CSharpCompilation)_semanticModel.Compilation; var iDisposable = enumeratorInfoOpt.IsAsync ? compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : compilation.GetSpecialType(SpecialType.System_IDisposable); info = new ForEachLoopOperationInfo(enumeratorInfoOpt.ElementType.GetPublicSymbol(), enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), isAsynchronous: enumeratorInfoOpt.IsAsync, needsDispose: enumeratorInfoOpt.NeedsDisposal, knownToImplementIDisposable: enumeratorInfoOpt.NeedsDisposal ? compilation.Conversions. ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, iDisposable, ref discardedUseSiteInfo).IsImplicit : false, enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(), enumeratorInfoOpt.CurrentConversion, boundForEachStatement.ElementConversion, getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorInfo is { Method: { IsExtensionMethod: true } } getEnumeratorInfo ? Operation.SetParentOperation( DeriveArguments( getEnumeratorInfo.Method, getEnumeratorInfo.Arguments, argumentsToParametersOpt: default, getEnumeratorInfo.DefaultArguments, getEnumeratorInfo.Expanded, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), null) : default, disposeArguments: enumeratorInfoOpt.PatternDisposeInfo is object ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default); } else { info = null; } return info; } internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) { if (boundForEachStatement.DeconstructionOpt != null) { return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); } else if (boundForEachStatement.IterationErrorExpressionOpt != null) { return Create(boundForEachStatement.IterationErrorExpressionOpt); } else { Debug.Assert(boundForEachStatement.IterationVariables.Length == 1); var local = boundForEachStatement.IterationVariables[0]; // We use iteration variable type syntax as the underlying syntax node as there is no variable declarator syntax in the syntax tree. var declaratorSyntax = boundForEachStatement.IterationVariableType.Syntax; return new VariableDeclaratorOperation(local.GetPublicSymbol(), initializer: null, ignoredArguments: ImmutableArray<IOperation>.Empty, semanticModel: _semanticModel, syntax: declaratorSyntax, isImplicit: false); } } private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) { IOperation loopControlVariable = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); IOperation collection = Create(boundForEachStatement.Expression); var nextVariables = ImmutableArray<IOperation>.Empty; IOperation body = Create(boundForEachStatement.Body); ForEachLoopOperationInfo? info = GetForEachLoopOperatorInfo(boundForEachStatement); ImmutableArray<ILocalSymbol> locals = boundForEachStatement.IterationVariables.GetPublicSymbols(); ILabelSymbol continueLabel = boundForEachStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForEachStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForEachStatement.Syntax; bool isImplicit = boundForEachStatement.WasCompilerGenerated; bool isAsynchronous = boundForEachStatement.AwaitOpt != null; return new ForEachLoopOperation(loopControlVariable, collection, nextVariables, info, isAsynchronous, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) { var body = (IBlockOperation)Create(boundTryStatement.TryBlock); ImmutableArray<ICatchClauseOperation> catches = CreateFromArray<BoundCatchBlock, ICatchClauseOperation>(boundTryStatement.CatchBlocks); var @finally = (IBlockOperation?)Create(boundTryStatement.FinallyBlockOpt); SyntaxNode syntax = boundTryStatement.Syntax; bool isImplicit = boundTryStatement.WasCompilerGenerated; return new TryOperation(body, catches, @finally, exitLabel: null, _semanticModel, syntax, isImplicit); } private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) { IOperation? exceptionDeclarationOrExpression = CreateVariableDeclarator((BoundLocal?)boundCatchBlock.ExceptionSourceOpt); // The exception filter prologue is introduced during lowering, so should be null here. Debug.Assert(boundCatchBlock.ExceptionFilterPrologueOpt is null); IOperation? filter = Create(boundCatchBlock.ExceptionFilterOpt); IBlockOperation handler = (IBlockOperation)Create(boundCatchBlock.Body); ITypeSymbol exceptionType = boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol() ?? _semanticModel.Compilation.ObjectType; ImmutableArray<ILocalSymbol> locals = boundCatchBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundCatchBlock.Syntax; bool isImplicit = boundCatchBlock.WasCompilerGenerated; return new CatchClauseOperation(exceptionDeclarationOrExpression, exceptionType, locals, filter, handler, _semanticModel, syntax, isImplicit); } private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) { IVariableDeclarationGroupOperation variables = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); IOperation body = Create(boundFixedStatement.Body); ImmutableArray<ILocalSymbol> locals = boundFixedStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundFixedStatement.Syntax; bool isImplicit = boundFixedStatement.WasCompilerGenerated; return new FixedOperation(locals, variables, body, _semanticModel, syntax, isImplicit); } private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) { Debug.Assert((boundUsingStatement.DeclarationsOpt == null) != (boundUsingStatement.ExpressionOpt == null)); Debug.Assert(boundUsingStatement.ExpressionOpt is object || boundUsingStatement.Locals.Length > 0); IOperation resources = Create(boundUsingStatement.DeclarationsOpt ?? (BoundNode)boundUsingStatement.ExpressionOpt!); IOperation body = Create(boundUsingStatement.Body); ImmutableArray<ILocalSymbol> locals = boundUsingStatement.Locals.GetPublicSymbols(); bool isAsynchronous = boundUsingStatement.AwaitOpt != null; DisposeOperationInfo disposeOperationInfo = boundUsingStatement.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default; SyntaxNode syntax = boundUsingStatement.Syntax; bool isImplicit = boundUsingStatement.WasCompilerGenerated; return new UsingOperation(resources, body, locals, isAsynchronous, disposeOperationInfo, _semanticModel, syntax, isImplicit); } private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) { IOperation? thrownObject = Create(boundThrowStatement.ExpressionOpt); SyntaxNode syntax = boundThrowStatement.Syntax; ITypeSymbol? statementType = null; bool isImplicit = boundThrowStatement.WasCompilerGenerated; return new ThrowOperation(thrownObject, _semanticModel, syntax, statementType, isImplicit); } private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) { IOperation? returnedValue = Create(boundReturnStatement.ExpressionOpt); SyntaxNode syntax = boundReturnStatement.Syntax; bool isImplicit = boundReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.Return, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) { IOperation returnedValue = Create(boundYieldReturnStatement.Expression); SyntaxNode syntax = boundYieldReturnStatement.Syntax; bool isImplicit = boundYieldReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldReturn, _semanticModel, syntax, isImplicit); } private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) { // If there is no Enter2 method, then there will be no lock taken reference bool legacyMode = _semanticModel.Compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2) == null; ILocalSymbol? lockTakenSymbol = legacyMode ? null : new SynthesizedLocal((_semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart) as IMethodSymbol).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)_semanticModel.Compilation).GetSpecialType(SpecialType.System_Boolean)), SynthesizedLocalKind.LockTaken, syntaxOpt: boundLockStatement.Argument.Syntax).GetPublicSymbol(); IOperation lockedValue = Create(boundLockStatement.Argument); IOperation body = Create(boundLockStatement.Body); SyntaxNode syntax = boundLockStatement.Syntax; bool isImplicit = boundLockStatement.WasCompilerGenerated; return new LockOperation(lockedValue, body, lockTakenSymbol, _semanticModel, syntax, isImplicit); } private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) { SyntaxNode syntax = boundBadStatement.Syntax; // if child has syntax node point to same syntax node as bad statement, then this invalid statement is implicit bool isImplicit = boundBadStatement.WasCompilerGenerated || boundBadStatement.ChildBoundNodes.Any(e => e?.Syntax == boundBadStatement.Syntax); var children = CreateFromArray<BoundNode, IOperation>(boundBadStatement.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type: null, constantValue: null, isImplicit); } private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) { var node = boundLocalDeclaration.Syntax; var kind = node.Kind(); SyntaxNode varStatement; SyntaxNode varDeclaration; switch (kind) { case SyntaxKind.LocalDeclarationStatement: { var statement = (LocalDeclarationStatementSyntax)node; // this happen for simple int i = 0; // var statement points to LocalDeclarationStatementSyntax varStatement = statement; varDeclaration = statement.Declaration; break; } case SyntaxKind.VariableDeclarator: { // this happen for 'for loop' initializer // We generate a DeclarationGroup for this scenario to maintain tree shape consistency across IOperation. // var statement points to VariableDeclarationSyntax Debug.Assert(node.Parent != null); varStatement = node.Parent; varDeclaration = node.Parent; break; } default: { Debug.Fail($"Unexpected syntax: {kind}"); // otherwise, they points to whatever bound nodes are pointing to. varStatement = varDeclaration = node; break; } } bool multiVariableImplicit = boundLocalDeclaration.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundLocalDeclaration, varDeclaration); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundLocalDeclaration, varDeclaration); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, varDeclaration, multiVariableImplicit); // In the case of a for loop, varStatement and varDeclaration will be the same syntax node. // We can only have one explicit operation, so make sure this node is implicit in that scenario. bool isImplicit = (varStatement == varDeclaration) || boundLocalDeclaration.WasCompilerGenerated; return new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, varStatement, isImplicit); } private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) { // The syntax for the boundMultipleLocalDeclarations can either be a LocalDeclarationStatement or a VariableDeclaration, depending on the context // (using/fixed statements vs variable declaration) // We generate a DeclarationGroup for these scenarios (using/fixed) to maintain tree shape consistency across IOperation. SyntaxNode declarationGroupSyntax = boundMultipleLocalDeclarations.Syntax; SyntaxNode declarationSyntax = declarationGroupSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)declarationGroupSyntax).Declaration : declarationGroupSyntax; bool declarationIsImplicit = boundMultipleLocalDeclarations.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundMultipleLocalDeclarations, declarationSyntax); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundMultipleLocalDeclarations, declarationSyntax); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, declarationSyntax, declarationIsImplicit); // If the syntax was the same, we're in a fixed statement or using statement. We make the Group operation implicit in this scenario, as the // syntax itself is a VariableDeclaration. We do this for using declarations as well, but since that doesn't have a separate parent bound // node, we need to check the current node for that explicitly. bool isImplicit = declarationGroupSyntax == declarationSyntax || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; var variableDeclaration = new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, declarationGroupSyntax, isImplicit); if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations usingDecl) { return new UsingDeclarationOperation( variableDeclaration, isAsynchronous: usingDecl.AwaitOpt is object, disposeInfo: usingDecl.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: usingDecl.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(usingDecl.PatternDisposeInfoOpt, usingDecl.Syntax)) : default, _semanticModel, declarationGroupSyntax, isImplicit: boundMultipleLocalDeclarations.WasCompilerGenerated); } return variableDeclaration; } private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) { ILabelSymbol label = boundLabelStatement.Label.GetPublicSymbol(); SyntaxNode syntax = boundLabelStatement.Syntax; bool isImplicit = boundLabelStatement.WasCompilerGenerated; return new LabeledOperation(label, operation: null, _semanticModel, syntax, isImplicit); } private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) { ILabelSymbol label = boundLabeledStatement.Label.GetPublicSymbol(); IOperation labeledStatement = Create(boundLabeledStatement.Body); SyntaxNode syntax = boundLabeledStatement.Syntax; bool isImplicit = boundLabeledStatement.WasCompilerGenerated; return new LabeledOperation(label, labeledStatement, _semanticModel, syntax, isImplicit); } private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) { // lambda body can point to expression directly and binder can insert expression statement there. and end up statement pointing to // expression syntax node since there is no statement syntax node to point to. this will mark such one as implicit since it doesn't // actually exist in code bool isImplicit = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; SyntaxNode syntax = boundExpressionStatement.Syntax; // If we're creating the tree for a speculatively-bound constructor initializer, there can be a bound sequence as the child node here // that corresponds to the lifetime of any declared variables. IOperation expression = Create(boundExpressionStatement.Expression); if (boundExpressionStatement.Expression is BoundSequence sequence) { Debug.Assert(boundExpressionStatement.Syntax == sequence.Value.Syntax); isImplicit = true; } return new ExpressionStatementOperation(expression, _semanticModel, syntax, isImplicit); } internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) { SyntaxNode syntax = boundTupleExpression.Syntax; bool isImplicit = boundTupleExpression.WasCompilerGenerated; ITypeSymbol? type = boundTupleExpression.GetPublicTypeSymbol(); if (syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { var tupleOperation = CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false); return new DeclarationExpressionOperation(tupleOperation, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } TypeSymbol? naturalType = boundTupleExpression switch { BoundTupleLiteral { Type: var t } => t, BoundConvertedTupleLiteral { SourceTuple: { Type: var t } } => t, BoundConvertedTupleLiteral => null, { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; ImmutableArray<IOperation> elements = CreateFromArray<BoundExpression, IOperation>(boundTupleExpression.Arguments); return new TupleOperation(elements, naturalType.GetPublicSymbol(), _semanticModel, syntax, type, isImplicit); } private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo = null) { Debug.Assert(positionInfo == null || boundInterpolatedString.InterpolationData == null); ImmutableArray<IInterpolatedStringContentOperation> parts = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, positionInfo ?? boundInterpolatedString.InterpolationData?.PositionInfo[0]); SyntaxNode syntax = boundInterpolatedString.Syntax; ITypeSymbol? type = boundInterpolatedString.GetPublicTypeSymbol(); ConstantValue? constantValue = boundInterpolatedString.ConstantValue; bool isImplicit = boundInterpolatedString.WasCompilerGenerated; return new InterpolatedStringOperation(parts, _semanticModel, syntax, type, constantValue, isImplicit); } internal ImmutableArray<IInterpolatedStringContentOperation> CreateBoundInterpolatedStringContentOperation(ImmutableArray<BoundExpression> parts, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo) { return positionInfo is { } info ? createHandlerInterpolatedStringContent(info) : createNonHandlerInterpolatedStringContent(); ImmutableArray<IInterpolatedStringContentOperation> createNonHandlerInterpolatedStringContent() { var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); foreach (var part in parts) { if (part.Kind == BoundKind.StringInsert) { builder.Add((IInterpolatedStringContentOperation)Create(part)); } else { builder.Add(CreateBoundInterpolatedStringTextOperation((BoundLiteral)part)); } } return builder.ToImmutableAndFree(); } ImmutableArray<IInterpolatedStringContentOperation> createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> positionInfo) { // For interpolated string handlers, we want to deconstruct the `AppendLiteral`/`AppendFormatted` calls into // their relevant components. // https://github.com/dotnet/roslyn/issues/54505 we need to handle interpolated strings used as handler conversions. Debug.Assert(parts.Length == positionInfo.Length); var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); for (int i = 0; i < parts.Length; i++) { var part = parts[i]; var currentPosition = positionInfo[i]; BoundExpression value; BoundExpression? alignment; BoundExpression? format; switch (part) { case BoundCall call: (value, alignment, format) = getCallInfo(call.Arguments, call.ArgumentNamesOpt, currentPosition); break; case BoundDynamicInvocation dynamicInvocation: (value, alignment, format) = getCallInfo(dynamicInvocation.Arguments, dynamicInvocation.ArgumentNamesOpt, currentPosition); break; case BoundBadExpression bad: Debug.Assert(bad.ChildBoundNodes.Length == 2 + // initial value + receiver is added to the end (currentPosition.HasAlignment ? 1 : 0) + (currentPosition.HasFormat ? 1 : 0)); value = bad.ChildBoundNodes[0]; if (currentPosition.IsLiteral) { alignment = format = null; } else { alignment = currentPosition.HasAlignment ? bad.ChildBoundNodes[1] : null; format = currentPosition.HasFormat ? bad.ChildBoundNodes[^2] : null; } break; default: throw ExceptionUtilities.UnexpectedValue(part.Kind); } // We are intentionally not checking the part for implicitness here. The part is a generated AppendLiteral or AppendFormatted call, // and will always be marked as CompilerGenerated. However, our existing behavior for non-builder interpolated strings does not mark // the BoundLiteral or BoundStringInsert components as compiler generated. This generates a non-implicit IInterpolatedStringTextOperation // with an implicit literal underneath, and a non-implicit IInterpolationOperation with non-implicit underlying components. bool isImplicit = false; if (currentPosition.IsLiteral) { Debug.Assert(alignment is null); Debug.Assert(format is null); IOperation valueOperation = value switch { BoundLiteral l => CreateBoundLiteralOperation(l, @implicit: true), BoundConversion { Operand: BoundLiteral } c => CreateBoundConversionOperation(c, forceOperandImplicitLiteral: true), _ => throw ExceptionUtilities.UnexpectedValue(value.Kind), }; Debug.Assert(valueOperation.IsImplicit); builder.Add(new InterpolatedStringTextOperation(valueOperation, _semanticModel, part.Syntax, isImplicit)); } else { IOperation valueOperation = Create(value); IOperation? alignmentOperation = Create(alignment); IOperation? formatOperation = Create(format); Debug.Assert(valueOperation.Syntax != part.Syntax); builder.Add(new InterpolationOperation(valueOperation, alignmentOperation, formatOperation, _semanticModel, part.Syntax, isImplicit)); } } return builder.ToImmutableAndFree(); static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) { BoundExpression value = arguments[0]; if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) { // There was no alignment/format component, as binding will qualify those parameters by name return (value, null, null); } else { var alignmentIndex = argumentNamesOpt.IndexOf("alignment"); BoundExpression? alignment = alignmentIndex == -1 ? null : arguments[alignmentIndex]; var formatIndex = argumentNamesOpt.IndexOf("format"); BoundExpression? format = formatIndex == -1 ? null : arguments[formatIndex]; return (value, alignment, format); } } } } private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) { IOperation expression = Create(boundStringInsert.Value); IOperation? alignment = Create(boundStringInsert.Alignment); IOperation? formatString = Create(boundStringInsert.Format); SyntaxNode syntax = boundStringInsert.Syntax; bool isImplicit = boundStringInsert.WasCompilerGenerated; return new InterpolationOperation(expression, alignment, formatString, _semanticModel, syntax, isImplicit); } private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) { IOperation text = CreateBoundLiteralOperation(boundNode, @implicit: true); SyntaxNode syntax = boundNode.Syntax; bool isImplicit = boundNode.WasCompilerGenerated; return new InterpolatedStringTextOperation(text, _semanticModel, syntax, isImplicit); } private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) { IOperation value = Create(boundConstantPattern.Value); SyntaxNode syntax = boundConstantPattern.Syntax; bool isImplicit = boundConstantPattern.WasCompilerGenerated; TypeSymbol inputType = boundConstantPattern.InputType; TypeSymbol narrowedType = boundConstantPattern.NarrowedType; return new ConstantPatternOperation(value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); IOperation value = Create(boundRelationalPattern.Value); SyntaxNode syntax = boundRelationalPattern.Syntax; bool isImplicit = boundRelationalPattern.WasCompilerGenerated; TypeSymbol inputType = boundRelationalPattern.InputType; TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; return new RelationalPatternOperation(operatorKind, value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) { ISymbol? variable = boundDeclarationPattern.Variable.GetPublicSymbol(); if (variable == null && boundDeclarationPattern.VariableAccess?.Kind == BoundKind.DiscardExpression) { variable = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); } ITypeSymbol inputType = boundDeclarationPattern.InputType.GetPublicSymbol(); ITypeSymbol narrowedType = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); bool acceptsNull = boundDeclarationPattern.IsVar; ITypeSymbol? matchedType = acceptsNull ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol(); SyntaxNode syntax = boundDeclarationPattern.Syntax; bool isImplicit = boundDeclarationPattern.WasCompilerGenerated; return new DeclarationPatternOperation(matchedType, acceptsNull, variable, inputType, narrowedType, _semanticModel, syntax, isImplicit); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) { ITypeSymbol matchedType = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundRecursivePattern.Deconstruction is { IsDefault: false } deconstructions ? deconstructions.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; ImmutableArray<IPropertySubpatternOperation> propertySubpatterns = boundRecursivePattern.Properties is { IsDefault: false } properties ? properties.SelectAsArray((p, arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType), (Fac: this, MatchedType: matchedType)) : ImmutableArray<IPropertySubpatternOperation>.Empty; return new RecursivePatternOperation( matchedType, boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, isImplicit: boundRecursivePattern.WasCompilerGenerated); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) { ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundITuplePattern.Subpatterns is { IsDefault: false } subpatterns ? subpatterns.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; return new RecursivePatternOperation( boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns: ImmutableArray<IPropertySubpatternOperation>.Empty, declaredSymbol: null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, isImplicit: boundITuplePattern.WasCompilerGenerated); } private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) { return new TypePatternOperation( matchedType: boundTypePattern.NarrowedType.GetPublicSymbol(), inputType: boundTypePattern.InputType.GetPublicSymbol(), narrowedType: boundTypePattern.NarrowedType.GetPublicSymbol(), semanticModel: _semanticModel, syntax: boundTypePattern.Syntax, isImplicit: boundTypePattern.WasCompilerGenerated); } private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) { return new NegatedPatternOperation( (IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, isImplicit: boundNegatedPattern.WasCompilerGenerated); } private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) { return new BinaryPatternOperation( boundBinaryPattern.Disjunction ? BinaryOperatorKind.Or : BinaryOperatorKind.And, (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, isImplicit: boundBinaryPattern.WasCompilerGenerated); } private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) { IOperation value = Create(boundSwitchStatement.Expression); ImmutableArray<ISwitchCaseOperation> cases = CreateFromArray<BoundSwitchSection, ISwitchCaseOperation>(boundSwitchStatement.SwitchSections); ImmutableArray<ILocalSymbol> locals = boundSwitchStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol exitLabel = boundSwitchStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundSwitchStatement.Syntax; bool isImplicit = boundSwitchStatement.WasCompilerGenerated; return new SwitchOperation(locals, value, cases, exitLabel, _semanticModel, syntax, isImplicit); } private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) { ImmutableArray<ICaseClauseOperation> clauses = CreateFromArray<BoundSwitchLabel, ICaseClauseOperation>(boundSwitchSection.SwitchLabels); ImmutableArray<IOperation> body = CreateFromArray<BoundStatement, IOperation>(boundSwitchSection.Statements); ImmutableArray<ILocalSymbol> locals = boundSwitchSection.Locals.GetPublicSymbols(); return new SwitchCaseOperation(clauses, body, locals, condition: null, _semanticModel, boundSwitchSection.Syntax, isImplicit: boundSwitchSection.WasCompilerGenerated); } private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) { IOperation value = Create(boundSwitchExpression.Expression); ImmutableArray<ISwitchExpressionArmOperation> arms = CreateFromArray<BoundSwitchExpressionArm, ISwitchExpressionArmOperation>(boundSwitchExpression.SwitchArms); bool isExhaustive; if (boundSwitchExpression.DefaultLabel != null) { Debug.Assert(boundSwitchExpression.DefaultLabel is GeneratedLabelSymbol); isExhaustive = false; } else { isExhaustive = true; } return new SwitchExpressionOperation( value, arms, isExhaustive, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); } private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); IOperation? guard = Create(boundSwitchExpressionArm.WhenClause); IOperation value = Create(boundSwitchExpressionArm.Value); return new SwitchExpressionArmOperation( pattern, guard, value, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); } private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) { SyntaxNode syntax = boundSwitchLabel.Syntax; bool isImplicit = boundSwitchLabel.WasCompilerGenerated; LabelSymbol label = boundSwitchLabel.Label; if (boundSwitchLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel) { Debug.Assert(boundSwitchLabel.Pattern.Kind == BoundKind.DiscardPattern); return new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern cp && cp.InputType.IsValidV6SwitchGoverningType()) { return new SingleValueCaseClauseOperation(Create(cp.Value), label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchLabel.Pattern); IOperation? guard = Create(boundSwitchLabel.WhenClause); return new PatternCaseClauseOperation(label.GetPublicSymbol(), pattern, guard, _semanticModel, syntax, isImplicit); } } private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) { IOperation value = Create(boundIsPatternExpression.Expression); IPatternOperation pattern = (IPatternOperation)Create(boundIsPatternExpression.Pattern); SyntaxNode syntax = boundIsPatternExpression.Syntax; ITypeSymbol? type = boundIsPatternExpression.GetPublicTypeSymbol(); bool isImplicit = boundIsPatternExpression.WasCompilerGenerated; return new IsPatternOperation(value, pattern, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) { if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) { // Currently we have no IOperation APIs for different query clauses or continuation. return Create(boundQueryClause.Value); } IOperation operation = Create(boundQueryClause.Value); SyntaxNode syntax = boundQueryClause.Syntax; ITypeSymbol? type = boundQueryClause.GetPublicTypeSymbol(); bool isImplicit = boundQueryClause.WasCompilerGenerated; return new TranslatedQueryOperation(operation, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) { // We do not have operation nodes for the bound range variables, just it's value. return Create(boundRangeVariable.Value); } private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) { return new DiscardOperation( ((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), isImplicit: boundNode.WasCompilerGenerated); } private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) { return new UnaryOperation( UnaryOperatorKind.Hat, Create(boundIndex.Operand), isLifted: boundIndex.Type.IsNullableType(), isChecked: false, operatorMethod: null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), constantValue: null, isImplicit: boundIndex.WasCompilerGenerated); } private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) { IOperation? left = Create(boundRange.LeftOperandOpt); IOperation? right = Create(boundRange.RightOperandOpt); return new RangeOperation( left, right, isLifted: boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), isImplicit: boundRange.WasCompilerGenerated); } private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) { return new DiscardPatternOperation( inputType: boundNode.InputType.GetPublicSymbol(), narrowedType: boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) { // We treat `c is { ... .Prop: <pattern> }` as `c is { ...: { Prop: <pattern> } }` SyntaxNode subpatternSyntax = subpattern.Syntax; BoundPropertySubpatternMember? member = subpattern.Member; IPatternOperation pattern = (IPatternOperation)Create(subpattern.Pattern); if (member is null) { var reference = OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray<IOperation>.Empty, isImplicit: true); return new PropertySubpatternOperation(reference, pattern, _semanticModel, subpatternSyntax, isImplicit: false); } // Create an operation for last property access: // `{ SingleProp: <pattern operation> }` // or // `.LastProp: <pattern operation>` portion (treated as `{ LastProp: <pattern operation> }`) var nameSyntax = member.Syntax; var inputType = getInputType(member, matchedType); IPropertySubpatternOperation? result = createPropertySubpattern(member.Symbol, pattern, inputType, nameSyntax, isSingle: member.Receiver is null); while (member.Receiver is not null) { member = member.Receiver; nameSyntax = member.Syntax; ITypeSymbol previousType = inputType; inputType = getInputType(member, matchedType); // Create an operation for a preceding property access: // { PrecedingProp: <previous pattern operation> } IPatternOperation nestedPattern = new RecursivePatternOperation( matchedType: previousType, deconstructSymbol: null, deconstructionSubpatterns: ImmutableArray<IPatternOperation>.Empty, propertySubpatterns: ImmutableArray.Create(result), declaredSymbol: null, previousType, narrowedType: previousType, semanticModel: _semanticModel, nameSyntax, isImplicit: true); result = createPropertySubpattern(member.Symbol, nestedPattern, inputType, nameSyntax, isSingle: false); } return result; IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation pattern, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) { Debug.Assert(nameSyntax is not null); IOperation reference; switch (symbol) { case FieldSymbol field: { var constantValue = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); reference = new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration: false, createReceiver(), _semanticModel, nameSyntax, type: field.Type.GetPublicSymbol(), constantValue, isImplicit: false); break; } case PropertySymbol property: { reference = new PropertyReferenceOperation(property.GetPublicSymbol(), ImmutableArray<IArgumentOperation>.Empty, createReceiver(), _semanticModel, nameSyntax, type: property.Type.GetPublicSymbol(), isImplicit: false); break; } default: { // We should expose the symbol in this case somehow: // https://github.com/dotnet/roslyn/issues/33175 reference = OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray<IOperation>.Empty, isImplicit: false); break; } } var syntaxForPropertySubpattern = isSingle ? subpatternSyntax : nameSyntax; return new PropertySubpatternOperation(reference, pattern, _semanticModel, syntaxForPropertySubpattern, isImplicit: !isSingle); IOperation? createReceiver() => symbol?.IsStatic == false ? new InstanceReferenceOperation(InstanceReferenceKind.PatternInput, _semanticModel, nameSyntax!, receiverType, isImplicit: true) : null; } static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol matchedType) => member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? matchedType; } private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = placeholder.Syntax; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); bool isImplicit = placeholder.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private ImmutableArray<IArgumentOperation> CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) { // can't be an extension method for dispose Debug.Assert(!patternDisposeInfo.Method.IsStatic); if (patternDisposeInfo.Method.ParameterCount == 0) { return ImmutableArray<IArgumentOperation>.Empty; } Debug.Assert(!patternDisposeInfo.Expanded || patternDisposeInfo.Method.GetParameters().Last().OriginalDefinition.Type.IsSZArray()); var args = DeriveArguments( patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax, invokedAsExtensionMethod: false); return Operation.SetParentOperation(args, null); } } }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IInterpolatedStringOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IInterpolatedStringExpression : SemanticModelTestBase { private static CSharpTestSource GetSource(string code, bool hasDefaultHandler) => hasDefaultHandler ? new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) } : code; [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_Empty(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: """") (Syntax: '$""""') Parts(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_OnlyTextPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""Only text part""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: ""Only text part"") (Syntax: '$""Only text part""') Parts(1): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'Only text part') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Only text part"", IsImplicit) (Syntax: 'Only text part') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_OnlyInterpolationPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""{1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_EmptyInterpolationPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""{}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{}') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Alignment: null FormatString: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1733: Expected expression // Console.WriteLine(/*<bind>*/$"{}"/*</bind>*/); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(8, 40) }; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_TextAndInterpolationParts(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(int x) { Console.WriteLine(/*<bind>*/$""String {x} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x}') Expression: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment(bool hasDefaultHandler) { string source = @" using System; internal class Class { private string x = string.Empty; private int y = 0; public void M() { Console.WriteLine(/*<bind>*/$""String {x,20} and {y:D3} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,20}') Expression: IFieldReferenceOperation: System.String Class.x (OperationKind.FieldReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'x') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y:D3}') Expression: IFieldReferenceOperation: System.Int32 Class.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'y') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InterpolationAndFormatAndAlignment(bool hasDefaultHandler) { string source = @" using System; internal class Class { private string x = string.Empty; private const int y = 0; public void M() { Console.WriteLine(/*<bind>*/$""String {x,y:D3}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x,y:D3}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,y:D3}') Expression: IFieldReferenceOperation: System.String Class.x (OperationKind.FieldReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'x') Alignment: IFieldReferenceOperation: System.Int32 Class.y (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 0) (Syntax: 'y') Instance Receiver: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InvocationInInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { string x = string.Empty; int y = 0; Console.WriteLine(/*<bind>*/$""String {x} and {M2(y)} and constant {1}""/*</bind>*/); } private string M2(int z) => z.ToString(); } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x}') Expression: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{M2(y)}') Expression: IInvocationOperation ( System.String Class.M2(System.Int32 z)) (OperationKind.Invocation, Type: System.String) (Syntax: 'M2(y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_NestedInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { string x = string.Empty; int y = 0; Console.WriteLine(/*<bind>*/$""String {M2($""{y}"")}""/*</bind>*/); } private int M2(string z) => Int32.Parse(z); } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {M2($""{y}"")}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{M2($""{y}"")}') Expression: IInvocationOperation ( System.Int32 Class.M2(System.String z)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2($""{y}"")') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: '$""{y}""') IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{y}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y}') Expression: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') Alignment: null FormatString: 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) Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InvalidExpressionInInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(int x) { Console.WriteLine(/*<bind>*/$""String {x1} and constant {Class}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""String {x ... nt {Class}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{x1}') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x1') Children(0) Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{Class}') Expression: IInvalidOperation (OperationKind.Invalid, Type: Class, IsInvalid, IsImplicit) (Syntax: 'Class') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Class') Alignment: null FormatString: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'x1' does not exist in the current context // Console.WriteLine(/*<bind>*/$"String {x1} and constant {Class}"/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 47), // CS0119: 'Class' is a type, which is not valid in the given context // Console.WriteLine(/*<bind>*/$"String {x1} and constant {Class}"/*</bind>*/); Diagnostic(ErrorCode.ERR_BadSKunknown, "Class").WithArguments("Class", "type").WithLocation(8, 65) }; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_Empty_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string p) /*<bind>*/{ p = $""""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $"""";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""""') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: """") (Syntax: '$""""') Parts(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_OnlyTextPart_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string p) /*<bind>*/{ p = $""Only text part""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""Only text part"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""Only text part""') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: ""Only text part"") (Syntax: '$""Only text part""') Parts(1): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'Only text part') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Only text part"", IsImplicit) (Syntax: 'Only text part') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_OnlyInterpolationPart_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string p) /*<bind>*/{ p = $""{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') 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: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c)}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_MultipleInterpolationParts_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string c2, string p) /*<bind>*/{ p = $""{(a ? b : c)}{c2}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') 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: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? ... : c)}{c2}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? b : c)}{c2}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c)}{c2}""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{c2}') Expression: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_TextAndInterpolationParts_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, bool a2, string b2, string c2, string p) /*<bind>*/{ p = $""String1 {(a ? b : c)} and String2 {(a2 ? b2 : c2)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') 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: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""Strin ... b2 : c2)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""Strin ... b2 : c2)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String1 { ... b2 : c2)}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String1 ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String1 "", IsImplicit) (Syntax: 'String1 ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and String2 ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and String2 "", IsImplicit) (Syntax: ' and String2 ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a2 ? b2 : c2)}') Expression: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a2 ? b2 : c2') Alignment: null FormatString: null Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string p) /*<bind>*/{ p = $""{(a ? b : c),20:D3}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') 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: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? ... c),20:D3}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? ... c),20:D3}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c),20:D3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c),20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow_02(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string b2, string c, string p) /*<bind>*/{ p = $""{b2,20:D3}{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{b2,2 ... ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{b2,2 ... ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b2,20:D3 ... ? b : c)}""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b2,20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b2') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow_03(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string b2, string b3, string c, string p) /*<bind>*/{ p = $""{b2,20:D3}{b3,21:D4}{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] [5] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b3') Value: IParameterReferenceOperation: b3 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b3') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '21') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 21) (Syntax: '21') 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: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{b2,2 ... ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{b2,2 ... ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b2,20:D3 ... ? b : c)}""') Parts(3): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b2,20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b2') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b3,21:D4}') Expression: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b3') Alignment: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 21, IsImplicit) (Syntax: '21') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D4"") (Syntax: ':D4') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_NestedInterpolation_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string a, int? b, int c) /*<bind>*/{ a = $""{$""{b ?? c}""}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.String) (Syntax: 'a') 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: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (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) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = $""{$""{b ?? c}""}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'a = $""{$""{b ?? c}""}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{$""{b ?? c}""}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{$""{b ?? c}""}') Expression: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b ?? c}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b ?? c}') Expression: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Alignment: null FormatString: null Alignment: null FormatString: null Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_ConditionalCodeInAlignment_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, int b, int c, string d, string p) /*<bind>*/{ p = $""{d,(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd') Value: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.String) (Syntax: 'd') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = $""{d,(a ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'p = $""{d,(a ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{d,(a ? b : c)}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{d,(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'd') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,18): error CS0150: A constant value is expected // p = $"{d,(a ? b : c)}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(a ? b : c)").WithLocation(8, 18) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_ConditionalCodeInAlignment_Flow_02(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string c2, string p) /*<bind>*/{ p = $""{c2,(a ? b : c):D3}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = $""{c2,( ... : c):D3}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'p = $""{c2,( ... b : c):D3}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{c2,(a ? b : c):D3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{c2,(a ? b : c):D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'c2') Alignment: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,20): error CS0029: Cannot implicitly convert type 'string' to 'int' // p = $"{c2,(a ? b : c):D3}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a ? b : c").WithArguments("string", "int").WithLocation(8, 20) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [Fact] public void InterpolatedStringHandlerConversion_01() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_02() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_03() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_04() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_05() { var code = @" using System.Runtime.CompilerServices; int i = 0; CustomHandler /*<bind>*/c = $""literal{i}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler {} "; var expectedDiagnostics = new[] { // (4,29): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""literal{i}""").WithArguments("CustomHandler", "2").WithLocation(4, 29), // (4,29): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""literal{i}""").WithArguments("CustomHandler", "3").WithLocation(4, 29), // (4,31): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 31), // (4,31): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "literal").WithArguments("?.()").WithLocation(4, 31), // (4,38): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{i}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 38), // (4,38): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{i}").WithArguments("?.()").WithLocation(4, 38) }; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c = $""literal{i}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= $""literal{i}""') IOperation: (OperationKind.None, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""literal{i}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null, IsInvalid) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsInvalid, IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i') Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_06() { var code = @" using System.Runtime.CompilerServices; int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) {} public void AppendFormatted(object o, object alignment, object format) {} public void AppendLiteral(object o) {} } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'literal') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: 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') FormatString: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: ':test') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_07() { var code = @" using System.Runtime.CompilerServices; CustomHandler /*<bind>*/c = $""{}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) {} public void AppendFormatted(object o, object alignment, object format) {} public void AppendLiteral(object o) {} } "; var expectedDiagnostics = new[] { // (3,32): error CS1733: Expected expression // CustomHandler /*<bind>*/c = $"{}"/*</bind>*/; Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(3, 32) }; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c = $""{}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= $""{}""') IOperation: (OperationKind.None, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{}') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void DynamicConstruction_01() { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(/*<bind>*/$""literal{d,1:format}""/*</bind>*/); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d, int alignment, string format) { Console.WriteLine(""AppendFormatted""); } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{d,1:format}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'literal') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{d,1:format}') Expression: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""format"") (Syntax: ':format') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void DynamicConstruction_02() { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, /*<bind>*/$""{1}literal""/*</bind>*/); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var expectedDiagnostics = new[] { // (4,16): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, /*<bind>*/$"{1}literal"/*</bind>*/); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, @"$""{1}literal""").WithArguments("CustomHandler").WithLocation(4, 16) }; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{1}literal""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, 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, IsInvalid) (Syntax: '1') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null, IsInvalid) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsInvalid, IsImplicit) (Syntax: 'literal') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void InterpolationEscapeConstantValue_WithDefaultHandler() { var code = @" int i = 1; System.Console.WriteLine(/*<bind>*/$""{{ {i} }}""/*</bind>*/);"; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{{ {i} }}""') Parts(3): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: '{{ ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{ "", IsImplicit) (Syntax: '{{ ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' }}') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" }"", IsImplicit) (Syntax: ' }}') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void InterpolationEscapeConstantValue_WithoutDefaultHandler() { var code = @" int i = 1; System.Console.WriteLine(/*<bind>*/$""{{ {i} }}""/*</bind>*/);"; var expectedDiagnostics = DiagnosticDescription.None; // The difference between this test and the previous one is the constant value of the ILiteralOperations. When handlers are involved, the // constant value is { and }. When they are not involved, the constant values are {{ and }} string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{{ {i} }}""') Parts(3): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: '{{ ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{{ "", IsImplicit) (Syntax: '{{ ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' }}') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" }}"", IsImplicit) (Syntax: ' }}') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" #pragma warning disable CS0219 // Unused local object o1; object o2; object o3; _ = /*<bind>*/$""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1/*</bind>*/; "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... null}"" + 1') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... o3 = null}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... o2 = null}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o1 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o1 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o1 = null') Left: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o1') 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) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o2 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o2 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o2 = null') Left: ILocalReferenceOperation: o2 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o2') 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) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o3 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o3 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o3 = null') Left: ILocalReferenceOperation: o3 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o3') 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) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: 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') "; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IInterpolatedStringExpression : SemanticModelTestBase { private static CSharpTestSource GetSource(string code, bool hasDefaultHandler) => hasDefaultHandler ? new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) } : code; [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_Empty(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: """") (Syntax: '$""""') Parts(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_OnlyTextPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""Only text part""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: ""Only text part"") (Syntax: '$""Only text part""') Parts(1): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'Only text part') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Only text part"", IsImplicit) (Syntax: 'Only text part') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_OnlyInterpolationPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""{1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_EmptyInterpolationPart(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { Console.WriteLine(/*<bind>*/$""{}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{}') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Alignment: null FormatString: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1733: Expected expression // Console.WriteLine(/*<bind>*/$"{}"/*</bind>*/); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(8, 40) }; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_TextAndInterpolationParts(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(int x) { Console.WriteLine(/*<bind>*/$""String {x} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x}') Expression: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment(bool hasDefaultHandler) { string source = @" using System; internal class Class { private string x = string.Empty; private int y = 0; public void M() { Console.WriteLine(/*<bind>*/$""String {x,20} and {y:D3} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,20}') Expression: IFieldReferenceOperation: System.String Class.x (OperationKind.FieldReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'x') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y:D3}') Expression: IFieldReferenceOperation: System.Int32 Class.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'y') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InterpolationAndFormatAndAlignment(bool hasDefaultHandler) { string source = @" using System; internal class Class { private string x = string.Empty; private const int y = 0; public void M() { Console.WriteLine(/*<bind>*/$""String {x,y:D3}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x,y:D3}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,y:D3}') Expression: IFieldReferenceOperation: System.String Class.x (OperationKind.FieldReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'x') Alignment: IFieldReferenceOperation: System.Int32 Class.y (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 0) (Syntax: 'y') Instance Receiver: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InvocationInInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { string x = string.Empty; int y = 0; Console.WriteLine(/*<bind>*/$""String {x} and {M2(y)} and constant {1}""/*</bind>*/); } private string M2(int z) => z.ToString(); } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x}') Expression: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{M2(y)}') Expression: IInvocationOperation ( System.String Class.M2(System.Int32 z)) (OperationKind.Invocation, Type: System.String) (Syntax: 'M2(y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_NestedInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M() { string x = string.Empty; int y = 0; Console.WriteLine(/*<bind>*/$""String {M2($""{y}"")}""/*</bind>*/); } private int M2(string z) => Int32.Parse(z); } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {M2($""{y}"")}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{M2($""{y}"")}') Expression: IInvocationOperation ( System.Int32 Class.M2(System.String z)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2($""{y}"")') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: '$""{y}""') IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{y}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y}') Expression: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') Alignment: null FormatString: 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) Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Theory, WorkItem(18300, "https://github.com/dotnet/roslyn/issues/18300")] [CombinatorialData] public void InterpolatedStringExpression_InvalidExpressionInInterpolation(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(int x) { Console.WriteLine(/*<bind>*/$""String {x1} and constant {Class}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""String {x ... nt {Class}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{x1}') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x1') Children(0) Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{Class}') Expression: IInvalidOperation (OperationKind.Invalid, Type: Class, IsInvalid, IsImplicit) (Syntax: 'Class') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Class') Alignment: null FormatString: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'x1' does not exist in the current context // Console.WriteLine(/*<bind>*/$"String {x1} and constant {Class}"/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 47), // CS0119: 'Class' is a type, which is not valid in the given context // Console.WriteLine(/*<bind>*/$"String {x1} and constant {Class}"/*</bind>*/); Diagnostic(ErrorCode.ERR_BadSKunknown, "Class").WithArguments("Class", "type").WithLocation(8, 65) }; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(GetSource(source, hasDefaultHandler), expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_Empty_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string p) /*<bind>*/{ p = $""""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $"""";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""""') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: """") (Syntax: '$""""') Parts(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_OnlyTextPart_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string p) /*<bind>*/{ p = $""Only text part""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""Only text part"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""Only text part""') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, Constant: ""Only text part"") (Syntax: '$""Only text part""') Parts(1): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'Only text part') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Only text part"", IsImplicit) (Syntax: 'Only text part') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_OnlyInterpolationPart_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string p) /*<bind>*/{ p = $""{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') 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: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c)}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_MultipleInterpolationParts_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string c2, string p) /*<bind>*/{ p = $""{(a ? b : c)}{c2}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') 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: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? ... : c)}{c2}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? b : c)}{c2}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c)}{c2}""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{c2}') Expression: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_TextAndInterpolationParts_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, bool a2, string b2, string c2, string p) /*<bind>*/{ p = $""String1 {(a ? b : c)} and String2 {(a2 ? b2 : c2)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') 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: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""Strin ... b2 : c2)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""Strin ... b2 : c2)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String1 { ... b2 : c2)}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String1 ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String1 "", IsImplicit) (Syntax: 'String1 ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and String2 ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and String2 "", IsImplicit) (Syntax: ' and String2 ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a2 ? b2 : c2)}') Expression: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a2 ? b2 : c2') Alignment: null FormatString: null Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string p) /*<bind>*/{ p = $""{(a ? b : c),20:D3}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') 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: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{(a ? ... c),20:D3}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{(a ? ... c),20:D3}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{(a ? b : c),20:D3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c),20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow_02(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string b2, string c, string p) /*<bind>*/{ p = $""{b2,20:D3}{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{b2,2 ... ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{b2,2 ... ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b2,20:D3 ... ? b : c)}""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b2,20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b2') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_FormatAndAlignment_Flow_03(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string b2, string b3, string c, string p) /*<bind>*/{ p = $""{b2,20:D3}{b3,21:D4}{(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] [5] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2') Value: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b2') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b3') Value: IParameterReferenceOperation: b3 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b3') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '21') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 21) (Syntax: '21') 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: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = $""{b2,2 ... ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'p = $""{b2,2 ... ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b2,20:D3 ... ? b : c)}""') Parts(3): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b2,20:D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b2') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b3,21:D4}') Expression: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b3') Alignment: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 21, IsImplicit) (Syntax: '21') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D4"") (Syntax: ':D4') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a ? b : c') Alignment: null FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_NestedInterpolation_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(string a, int? b, int c) /*<bind>*/{ a = $""{$""{b ?? c}""}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.String) (Syntax: 'a') 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: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (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) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = $""{$""{b ?? c}""}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'a = $""{$""{b ?? c}""}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'a') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{$""{b ?? c}""}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{$""{b ?? c}""}') Expression: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{b ?? c}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{b ?? c}') Expression: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Alignment: null FormatString: null Alignment: null FormatString: null Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_ConditionalCodeInAlignment_Flow(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, int b, int c, string d, string p) /*<bind>*/{ p = $""{d,(a ? b : c)}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd') Value: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.String) (Syntax: 'd') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = $""{d,(a ? b : c)}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'p = $""{d,(a ? b : c)}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{d,(a ? b : c)}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{d,(a ? b : c)}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'd') Alignment: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') FormatString: null Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,18): error CS0150: A constant value is expected // p = $"{d,(a ? b : c)}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(a ? b : c)").WithLocation(8, 18) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Theory] [CombinatorialData] public void InterpolatedStringExpression_ConditionalCodeInAlignment_Flow_02(bool hasDefaultHandler) { string source = @" using System; internal class Class { public void M(bool a, string b, string c, string c2, string p) /*<bind>*/{ p = $""{c2,(a ? b : c):D3}""; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.String) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'c2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = $""{c2,( ... : c):D3}"";') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'p = $""{c2,( ... b : c):D3}""') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'p') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{c2,(a ? b : c):D3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{c2,(a ? b : c):D3}') Expression: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'c2') Alignment: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'a ? b : c') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,20): error CS0029: Cannot implicitly convert type 'string' to 'int' // p = $"{c2,(a ? b : c):D3}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a ? b : c").WithArguments("string", "int").WithLocation(8, 20) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(GetSource(source, hasDefaultHandler), expectedFlowGraph, expectedDiagnostics); } [Fact] public void InterpolatedStringHandlerConversion_01() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_02() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_03() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i:test}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_04() { var code = @" int i = 0; CustomHandler /*<bind>*/c = $""literal{i}""/*</bind>*/; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, handler }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_05() { var code = @" using System.Runtime.CompilerServices; int i = 0; CustomHandler /*<bind>*/c = $""literal{i}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler {} "; var expectedDiagnostics = new[] { // (4,29): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""literal{i}""").WithArguments("CustomHandler", "2").WithLocation(4, 29), // (4,29): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""literal{i}""").WithArguments("CustomHandler", "3").WithLocation(4, 29), // (4,31): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 31), // (4,31): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "literal").WithArguments("?.()").WithLocation(4, 31), // (4,38): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{i}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 38), // (4,38): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler /*<bind>*/c = $"literal{i}"/*</bind>*/; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{i}").WithArguments("?.()").WithLocation(4, 38) }; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c = $""literal{i}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= $""literal{i}""') IOperation: (OperationKind.None, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""literal{i}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""literal{i}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null, IsInvalid) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsInvalid, IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i') Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_06() { var code = @" using System.Runtime.CompilerServices; int i = 0; CustomHandler /*<bind>*/c = $""literal{i,1:test}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) {} public void AppendFormatted(object o, object alignment, object format) {} public void AppendLiteral(object o) {} } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = $""literal{i,1:test}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= $""literal{i,1:test}""') IOperation: (OperationKind.None, Type: CustomHandler, IsImplicit) (Syntax: '$""literal{i,1:test}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{i,1:test}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'literal') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i,1:test}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: 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') FormatString: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: ':test') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: ':test') "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringHandlerConversion_07() { var code = @" using System.Runtime.CompilerServices; CustomHandler /*<bind>*/c = $""{}""/*</bind>*/; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) {} public void AppendFormatted(object o, object alignment, object format) {} public void AppendLiteral(object o) {} } "; var expectedDiagnostics = new[] { // (3,32): error CS1733: Expected expression // CustomHandler /*<bind>*/c = $"{}"/*</bind>*/; Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(3, 32) }; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: CustomHandler c) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c = $""{}""') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= $""{}""') IOperation: (OperationKind.None, Type: CustomHandler, IsInvalid, IsImplicit) (Syntax: '$""{}""') Children(1): IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{}') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Alignment: null FormatString: null "; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void DynamicConstruction_01() { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(/*<bind>*/$""literal{d,1:format}""/*</bind>*/); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d, int alignment, string format) { Console.WriteLine(""AppendFormatted""); } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""literal{d,1:format}""') Parts(2): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'literal') Text: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'literal') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsImplicit) (Syntax: 'literal') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{d,1:format}') Expression: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""format"") (Syntax: ':format') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, InterpolatedStringHandlerAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void DynamicConstruction_02() { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, /*<bind>*/$""{1}literal""/*</bind>*/); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var expectedDiagnostics = new[] { // (4,16): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, /*<bind>*/$"{1}literal"/*</bind>*/); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, @"$""{1}literal""").WithArguments("CustomHandler").WithLocation(4, 16) }; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String, IsInvalid) (Syntax: '$""{1}literal""') Parts(2): IInterpolationOperation (OperationKind.Interpolation, Type: null, IsInvalid) (Syntax: '{1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, 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, IsInvalid) (Syntax: '1') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null, IsInvalid) (Syntax: 'literal') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""literal"", IsInvalid, IsImplicit) (Syntax: 'literal') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void InterpolationEscapeConstantValue_WithDefaultHandler() { var code = @" int i = 1; System.Console.WriteLine(/*<bind>*/$""{{ {i} }}""/*</bind>*/);"; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{{ {i} }}""') Parts(3): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: '{{ ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{ "", IsImplicit) (Syntax: '{{ ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' }}') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" }"", IsImplicit) (Syntax: ' }}') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void InterpolationEscapeConstantValue_WithoutDefaultHandler() { var code = @" int i = 1; System.Console.WriteLine(/*<bind>*/$""{{ {i} }}""/*</bind>*/);"; var expectedDiagnostics = DiagnosticDescription.None; // The difference between this test and the previous one is the constant value of the ILiteralOperations. When handlers are involved, the // constant value is { and }. When they are not involved, the constant values are {{ and }} string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{{ {i} }}""') Parts(3): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: '{{ ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{{ "", IsImplicit) (Syntax: '{{ ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' }}') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" }}"", IsImplicit) (Syntax: ' }}') "; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(new[] { code }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" #pragma warning disable CS0219 // Unused local object o1; object o2; object o3; _ = /*<bind>*/$""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1/*</bind>*/; "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... null}"" + 1') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... o3 = null}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{o1 = nul ... o2 = null}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o1 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o1 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o1 = null') Left: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o1') 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) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o2 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o2 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o2 = null') Left: ILocalReferenceOperation: o2 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o2') 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) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{o3 = null}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{o3 = null}') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'o3 = null') Left: ILocalReferenceOperation: o3 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o3') 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) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Alignment: null FormatString: null Right: 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') "; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ParenthesizedInterpolatedStringsAdded() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = /*<bind>*/(($""{i1,1:d}"" + $""{i2,2:f}"") + $""{i3,3:g}"") + ($""{i4,4:h}"" + ($""{i5,5:i}"" + $""{i6,6:j}""))/*</bind>*/; "; var expectedDiagnostics = DiagnosticDescription.None; var expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '(($""{i1,1:d ... {i6,6:j}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1,1:d} ... $""{i3,3:g}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1,1:d}"" ... $""{i2,2:f}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1,1:d}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1,1:d}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""d"") (Syntax: ':d') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2,2:f}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2,2:f}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""f"") (Syntax: ':f') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3,3:g}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3,3:g}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""g"") (Syntax: ':g') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4,4:h}"" ... ""{i6,6:j}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4,4:h}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4,4:h}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""h"") (Syntax: ':h') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i5,5:i}"" ... $""{i6,6:j}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5,5:i}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5,5:i}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""i"") (Syntax: ':i') Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6,6:j}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6,6:j}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6') FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""j"") (Syntax: ':j') "; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } } }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Test/Semantic/Semantics/InterpolationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class InterpolationTests : CompilingTestBase { [Fact] public void TestSimpleInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number }.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 }.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 }.""); Console.WriteLine($""Jenny don\'t change your number { number :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}.""); Console.WriteLine($""{number}""); } }"; string expectedOutput = @"Jenny don't change your number 8675309. Jenny don't change your number 8675309 . Jenny don't change your number 8675309. Jenny don't change your number 867-5309. Jenny don't change your number 867-5309 . Jenny don't change your number 867-5309. 8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestOnlyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}""); } }"; string expectedOutput = @"8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}{number}""); } }"; string expectedOutput = @"86753098675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}.""); } }"; string expectedOutput = @"Jenny don't change your number 867-5309 867-5309."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestEmptyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }.""); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,73): error CS1733: Expected expression // Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }."); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73) ); } [Fact] public void TestHalfOpenInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,63): error CS1010: Newline in constant // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63), // (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 // ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS8077: A single-line comment may not be used in an interpolated string. // Console.WriteLine($"Jenny don\'t change your number { 8675309 // "); Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp03() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 /* ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS1035: End-of-file found, '*/' expected // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71), // (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77), // (7,2): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2), // (7,2): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void LambdaInInterp() { string source = @"using System; class Program { static void Main(string[] args) { //Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() }); Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}""); } static int number = 8675309; } "; string expectedOutput = @"jenny (408) 867-5309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OneLiteral() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""Hello"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Hello"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } [Fact] public void OneInsert() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; Console.WriteLine( $""{hello}"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldstr ""Hello"" IL_0005: dup IL_0006: brtrue.s IL_000e IL_0008: pop IL_0009: ldstr """" IL_000e: call ""void System.Console.WriteLine(string)"" IL_0013: ret } "); } [Fact] public void TwoInserts() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $""{hello}, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TwoInserts02() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $@""{ hello }, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")] public void DynamicInterpolation() { string source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { dynamic nil = null; dynamic a = new string[] {""Hello"", ""world""}; Console.WriteLine($""<{nil}>""); Console.WriteLine($""<{a}>""); } Expression<Func<string>> M(dynamic d) { return () => $""Dynamic: {d}""; } }"; string expectedOutput = @"<> <System.String[]>"; var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnclosedInterpolation01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31), // (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35), // (7,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6), // (7,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6), // (8,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2)); } [Fact] public void UnclosedInterpolation02() { string source = @"class Program { static void Main(string[] args) { var x = $"";"; // The precise error messages are not important, but this must be an error. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,19): error CS1010: Newline in constant // var x = $"; Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19), // (5,20): error CS1002: ; expected // var x = $"; Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20) ); } [Fact] public void EmptyFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:}"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8089: Empty format specifier. // Console.WriteLine( $"{3:}" ); Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $"{3:d }" ); Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $@"{3:d Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d ").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS1733: Expected expression // Console.WriteLine( $"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32) ); } [Fact] public void MissingInterpolationExpression02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS1733: Expected expression // Console.WriteLine( $@"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression03() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( "; var normal = "$\""; var verbat = "$@\""; // ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail) Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline01() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" "" } ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline02() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" ""} ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void PreprocessorInsideInterpolation() { string source = @"class Program { static void Main() { var s = $@""{ #region : #endregion 0 }""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void EscapedCurly() { string source = @"class Program { static void Main() { var s1 = $"" \u007B ""; var s2 = $"" \u007D""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string. // var s1 = $" \u007B "; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21), // (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var s2 = $" \u007D"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21) ); } [Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")] public void NoFillIns01() { string source = @"class Program { static void Main() { System.Console.Write($""{{ x }}""); System.Console.WriteLine($@""This is a test""); } }"; string expectedOutput = @"{ x }This is a test"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BadAlignment() { string source = @"class Program { static void Main() { var s = $""{1,1E10}""; var t = $""{1,(int)1E10}""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22), // (5,22): error CS0150: A constant value is expected // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22), // (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override) // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22), // (6,22): error CS0150: A constant value is expected // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22) ); } [Fact] public void NestedInterpolatedVerbatim() { string source = @"using System; class Program { static void Main(string[] args) { var s = $@""{$@""{1}""}""; Console.WriteLine(s); } }"; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } // Since the platform type System.FormattableString is not yet in our platforms (at the // time of writing), we explicitly include the required platform types into the sources under test. private const string formattableString = @" /*============================================================ ** ** Class: FormattableString ** ** ** Purpose: implementation of the FormattableString ** class. ** ===========================================================*/ namespace System { /// <summary> /// A composite format string along with the arguments to be formatted. An instance of this /// type may result from the use of the C# or VB language primitive ""interpolated string"". /// </summary> public abstract class FormattableString : IFormattable { /// <summary> /// The composite format string. /// </summary> public abstract string Format { get; } /// <summary> /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> public abstract object[] GetArguments(); /// <summary> /// The number of arguments to be formatted. /// </summary> public abstract int ArgumentCount { get; } /// <summary> /// Returns one argument to be formatted from argument position <paramref name=""index""/>. /// </summary> public abstract object GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } /// <summary> /// Format the given object in the invariant culture. This static method may be /// imported in C# by /// <code> /// using static System.FormattableString; /// </code>. /// Within the scope /// of that import directive an interpolated string may be formatted in the /// invariant culture by writing, for example, /// <code> /// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"") /// </code> /// </summary> public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException(""formattable""); } return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); } } } /*============================================================ ** ** Class: FormattableStringFactory ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref=""FormattableString""/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format, params object[] arguments) { if (format == null) { throw new ArgumentNullException(""format""); } if (arguments == null) { throw new ArgumentNullException(""arguments""); } return new ConcreteFormattableString(format, arguments); } private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } public override object[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); } } } } "; [Fact] public void TargetType01() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; Console.Write(f is System.FormattableString); } }"; CompileAndVerify(source + formattableString, expectedOutput: "True"); } [Fact] public void TargetType02() { string source = @"using System; interface I1 { void M(String s); } interface I2 { void M(FormattableString s); } interface I3 { void M(IFormattable s); } interface I4 : I1, I2 {} interface I5 : I1, I3 {} interface I6 : I2, I3 {} interface I7 : I1, I2, I3 {} class C : I1, I2, I3, I4, I5, I6, I7 { public void M(String s) { Console.Write(1); } public void M(FormattableString s) { Console.Write(2); } public void M(IFormattable s) { Console.Write(3); } } class Program { public static void Main(string[] args) { C c = new C(); ((I1)c).M($""""); ((I2)c).M($""""); ((I3)c).M($""""); ((I4)c).M($""""); ((I5)c).M($""""); ((I6)c).M($""""); ((I7)c).M($""""); ((C)c).M($""""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "12311211"); } [Fact] public void MissingHelper() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; } }"; CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics( // (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported // IFormattable f = $"test"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26) ); } [Fact] public void AsyncInterp() { string source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { Task<string> hello = Task.FromResult(""Hello""); Task<string> world = Task.FromResult(""world""); M(hello, world).Wait(); } public static async Task M(Task<string> hello, Task<string> world) { Console.WriteLine($""{ await hello }, { await world }!""); } }"; CompileAndVerify( source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty); } [Fact] public void AlignmentExpression() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , -(3+4) }.""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "X = 123 ."); } [Fact] public void AlignmentMagnitude() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , (32768) }.""); Console.WriteLine($""X = { 123 , -(32768) }.""); Console.WriteLine($""X = { 123 , (32767) }.""); Console.WriteLine($""X = { 123 , -(32767) }.""); Console.WriteLine($""X = { 123 , int.MaxValue }.""); Console.WriteLine($""X = { 123 , int.MinValue }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , (32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42), // (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , -(32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41), // (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MaxValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41), // (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MinValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41) ); } [WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")] [Fact] public void InterpolationExpressionMustBeValue01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { String }.""); Console.WriteLine($""X = { null }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS0119: 'string' is a type, which is not valid in the given context // Console.WriteLine($"X = { String }."); Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35) ); } [Fact] public void InterpolationExpressionMustBeValue02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { x=>3 }.""); Console.WriteLine($""X = { Program.Main }.""); Console.WriteLine($""X = { Program.Main(null) }.""); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35), // (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS8917: The delegate type could not be inferred. // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x=>3").WithLocation(5, 35), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib01() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (15,21): error CS0117: 'string' does not contain a definition for 'Format' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib02() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Boolean Format(string format, int arg) { return true; } } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21) ); } [Fact] public void SillyCoreLib01() { var text = @"namespace System { interface IFormattable { } namespace Runtime.CompilerServices { public static class FormattableStringFactory { public static Bozo Create(string format, int arg) { return new Bozo(); } } } public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Bozo Format(string format, int arg) { return new Bozo(); } } public class FormattableString { } public class Bozo { public static implicit operator string(Bozo bozo) { return ""zz""; } public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); } } internal class Program { public static void Main() { var s1 = $""X = { 1 } ""; FormattableString s2 = $""X = { 1 } ""; } } }"; var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var compilation = CompileAndVerify(comp, verify: Verification.Fails); compilation.VerifyIL("System.Program.Main", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldstr ""X = {0} "" IL_0005: ldc.i4.1 IL_0006: call ""System.Bozo string.Format(string, int)"" IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)"" IL_0010: pop IL_0011: ldstr ""X = {0} "" IL_0016: ldc.i4.1 IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)"" IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)"" IL_0021: pop IL_0022: ret }"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax01() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):\}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40), // (6,40): error CS1009: Unrecognized escape sequence // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40) ); } [WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")] [Fact] public void Syntax02() { var text = @"using S = System; class C { void M() { var x = $""{ (S: } }"; // the precise diagnostics do not matter, as long as it is an error and not a crash. Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax03() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):}}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // var x = $"{ Math.Abs(value: 1):}}"; Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18) ); } [WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")] [Fact] public void NoUnexpandedForm() { string source = @"using System; class Program { public static void Main(string[] args) { string[] arr1 = new string[] { ""xyzzy"" }; object[] arr2 = arr1; Console.WriteLine($""-{null}-""); Console.WriteLine($""-{arr1}-""); Console.WriteLine($""-{arr2}-""); } }"; CompileAndVerify(source + formattableString, expectedOutput: @"-- -System.String[]- -System.String[]-"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Dynamic01() { var text = @"class C { const dynamic a = a; string s = $""{0,a}""; }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition // const dynamic a = a; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19), // (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null. // const dynamic a = a; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23), // (4,21): error CS0150: A constant value is expected // string s = $"{0,a}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21) ); } [WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")] [Fact] public void Syntax04() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<string>> e = () => $""\u1{0:\u2}""; Console.WriteLine(e); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,46): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46), // (8,52): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52) ); } [Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")] public void MissingConversionFromFormattableStringToIFormattable() { var text = @"namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) { return null; } } } namespace System { public abstract class FormattableString { } } static class C { static void Main() { System.IFormattable i = $""{""""}""; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics( // (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable' // System.IFormattable i = $"{""}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33) ); } [Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")] [InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")] [InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")] public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents) { var code = @" using System; Console.WriteLine(TwoComponents()); Console.WriteLine(ThreeComponents()); Console.WriteLine(FourComponents()); Console.WriteLine(FiveComponents()); string TwoComponents() { string s1 = ""1""; string s2 = ""2""; return " + twoComponents + @"; } string ThreeComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; return " + threeComponents + @"; } string FourComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; return " + fourComponents + @"; } string FiveComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; string s5 = ""5""; return " + fiveComponents + @"; } "; var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @" 12 123 1234 value:1 value:2 value:3 value:4 value:5 "); verifier.VerifyIL("Program.<<Main>$>g__TwoComponents|0_0()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (string V_0) //s2 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call ""string string.Concat(string, string)"" IL_0011: ret } "); verifier.VerifyIL("Program.<<Main>$>g__ThreeComponents|0_1()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (string V_0, //s2 string V_1) //s3 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldloc.0 IL_0012: ldloc.1 IL_0013: call ""string string.Concat(string, string, string)"" IL_0018: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FourComponents|0_2()", @" { // Code size 32 (0x20) .maxstack 4 .locals init (string V_0, //s2 string V_1, //s3 string V_2) //s4 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldstr ""4"" IL_0016: stloc.2 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""string string.Concat(string, string, string, string)"" IL_001f: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FiveComponents|0_3()", @" { // Code size 89 (0x59) .maxstack 3 .locals init (string V_0, //s1 string V_1, //s2 string V_2, //s3 string V_3, //s4 string V_4, //s5 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5) IL_0000: ldstr ""1"" IL_0005: stloc.0 IL_0006: ldstr ""2"" IL_000b: stloc.1 IL_000c: ldstr ""3"" IL_0011: stloc.2 IL_0012: ldstr ""4"" IL_0017: stloc.3 IL_0018: ldstr ""5"" IL_001d: stloc.s V_4 IL_001f: ldloca.s V_5 IL_0021: ldc.i4.0 IL_0022: ldc.i4.5 IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0030: ldloca.s V_5 IL_0032: ldloc.1 IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0038: ldloca.s V_5 IL_003a: ldloc.2 IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0040: ldloca.s V_5 IL_0042: ldloc.3 IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0048: ldloca.s V_5 IL_004a: ldloc.s V_4 IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0051: ldloca.s V_5 IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0058: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandler_OverloadsAndBoolReturns( bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @"int a = 1; System.Console.WriteLine(" + expression + @");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 80 (0x50) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldstr ""X"" IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.2 IL_0039: ldstr ""Y"" IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: ldloca.s V_1 IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0021: ldloca.s V_1 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 92 (0x5c) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_004d IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: brfalse.s IL_004d IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: brfalse.s IL_004d IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldstr ""X"" IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003b: brfalse.s IL_004d IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: br.s IL_004e IL_004d: ldc.i4.0 IL_004e: pop IL_004f: ldloca.s V_1 IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0056: call ""void System.Console.WriteLine(string)"" IL_005b: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_0051 IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0023: brfalse.s IL_0051 IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: brfalse.s IL_0051 IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldc.i4.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0047 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 88 (0x58) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004b IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: ldc.i4.0 IL_0033: ldstr ""X"" IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: ldloca.s V_1 IL_004d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0052: call ""void System.Console.WriteLine(string)"" IL_0057: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0051 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0051 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: brfalse.s IL_0051 IL_0027: ldloca.s V_1 IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0030: brfalse.s IL_0051 IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 100 (0x64) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0055 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0055 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0027: brfalse.s IL_0055 IL_0029: ldloca.s V_1 IL_002b: ldloc.0 IL_002c: ldc.i4.1 IL_002d: ldnull IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0033: brfalse.s IL_0055 IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.0 IL_0039: ldstr ""X"" IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: brfalse.s IL_0055 IL_0045: ldloca.s V_1 IL_0047: ldloc.0 IL_0048: ldc.i4.2 IL_0049: ldstr ""Y"" IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0053: br.s IL_0056 IL_0055: ldc.i4.0 IL_0056: pop IL_0057: ldloca.s V_1 IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005e: call ""void System.Console.WriteLine(string)"" IL_0063: ret } ", }; } [Fact] public void UseOfSpanInInterpolationHole_CSharp9() { var source = @" using System; ReadOnlySpan<char> span = stackalloc char[1]; Console.WriteLine($""{span}"");"; var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // Console.WriteLine($"{span}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22) ); } [ConditionalTheory(typeof(MonoOrCoreClrOnly))] [CombinatorialData] public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @" using System; ReadOnlySpan<char> a = ""1""; System.Console.WriteLine(" + expression + ");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldstr ""X"" IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: ldstr ""Y"" IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002a: ldloca.s V_1 IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0034: ldloca.s V_1 IL_0036: ldloc.0 IL_0037: ldc.i4.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 101 (0x65) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_0056 IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002a: brfalse.s IL_0056 IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: brfalse.s IL_0056 IL_0037: ldloca.s V_1 IL_0039: ldloc.0 IL_003a: ldstr ""X"" IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0044: brfalse.s IL_0056 IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: pop IL_0058: ldloca.s V_1 IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_005a IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002c: brfalse.s IL_005a IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: brfalse.s IL_005a IL_003a: ldloca.s V_1 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0050 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005a IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005a IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002e: brfalse.s IL_005a IL_0030: ldloca.s V_1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0039: brfalse.s IL_005a IL_003b: ldloca.s V_1 IL_003d: ldloc.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 97 (0x61) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0054 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: ldc.i4.0 IL_0028: ldnull IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: ldloca.s V_1 IL_003a: ldloc.0 IL_003b: ldc.i4.0 IL_003c: ldstr ""X"" IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: ldloca.s V_1 IL_0056: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005b: call ""void System.Console.WriteLine(string)"" IL_0060: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 109 (0x6d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005e IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005e IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0030: brfalse.s IL_005e IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldc.i4.1 IL_0036: ldnull IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_003c: brfalse.s IL_005e IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: ldstr ""X"" IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: brfalse.s IL_005e IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: ldc.i4.2 IL_0052: ldstr ""Y"" IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_005c: br.s IL_005f IL_005e: ldc.i4.0 IL_005f: pop IL_0060: ldloca.s V_1 IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0067: call ""void System.Console.WriteLine(string)"" IL_006c: ret } ", }; } [Theory] [InlineData(@"$""base{Throw()}{a = 2}""")] [InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")] public void BoolReturns_ShortCircuit(string expression) { var source = @" using System; int a = 1; Console.Write(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception();"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false"); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base 1"); } [Theory] [CombinatorialData] public void BoolOutParameter_ShortCircuits(bool useBoolReturns, [CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression) { var source = @" using System; int a = 1; Console.WriteLine(a); Console.WriteLine(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception(); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 1"); } [Theory] [InlineData(@"$""base{await Hole()}""")] [InlineData(@"$""base"" + $""{await Hole()}""")] public void AwaitInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @" { // Code size 164 (0xa4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00a3 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base{0}"" IL_0067: ldloc.1 IL_0068: box ""int"" IL_006d: call ""string string.Format(string, object)"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0090 } catch System.Exception { IL_0079: stloc.3 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0088: ldloc.3 IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008e: leave.s IL_00a3 } IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a3: ret } " : @" { // Code size 174 (0xae) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00ad IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base"" IL_0067: ldstr ""{0}"" IL_006c: ldloc.1 IL_006d: box ""int"" IL_0072: call ""string string.Format(string, object)"" IL_0077: call ""string string.Concat(string, string)"" IL_007c: call ""void System.Console.WriteLine(string)"" IL_0081: leave.s IL_009a } catch System.Exception { IL_0083: stloc.3 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0092: ldloc.3 IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0098: leave.s IL_00ad } IL_009a: ldarg.0 IL_009b: ldc.i4.s -2 IL_009d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00a2: ldarg.0 IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00ad: ret }"); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = await Hole(); Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base value:1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 185 (0xb9) .maxstack 3 .locals init (int V_0, int V_1, //hole System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00b8 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldc.i4.4 IL_0063: ldc.i4.1 IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0069: stloc.3 IL_006a: ldloca.s V_3 IL_006c: ldstr ""base"" IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0076: ldloca.s V_3 IL_0078: ldloc.1 IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_007e: ldloca.s V_3 IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0085: call ""void System.Console.WriteLine(string)"" IL_008a: leave.s IL_00a5 } catch System.Exception { IL_008c: stloc.s V_4 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009c: ldloc.s V_4 IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a3: leave.s IL_00b8 } IL_00a5: ldarg.0 IL_00a6: ldc.i4.s -2 IL_00a8: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00ad: ldarg.0 IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b8: ret } "); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = 2; Test(await M(1), " + expression + @", await M(3)); void Test(int i1, string s, int i2) => Console.WriteLine(s); Task<int> M(int i) { Console.WriteLine(i); return Task.FromResult(1); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 3 base value:2"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 328 (0x148) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0050 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00dc IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: stfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0018: ldc.i4.1 IL_0019: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0023: stloc.2 IL_0024: ldloca.s V_2 IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002b: brtrue.s IL_006c IL_002d: ldarg.0 IL_002e: ldc.i4.0 IL_002f: dup IL_0030: stloc.0 IL_0031: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0036: ldarg.0 IL_0037: ldloc.2 IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003d: ldarg.0 IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0043: ldloca.s V_2 IL_0045: ldarg.0 IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004b: leave IL_0147 IL_0050: ldarg.0 IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0056: stloc.2 IL_0057: ldarg.0 IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0063: ldarg.0 IL_0064: ldc.i4.m1 IL_0065: dup IL_0066: stloc.0 IL_0067: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006c: ldarg.0 IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0079: ldarg.0 IL_007a: ldc.i4.4 IL_007b: ldc.i4.1 IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0081: stloc.3 IL_0082: ldloca.s V_3 IL_0084: ldstr ""base"" IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_008e: ldloca.s V_3 IL_0090: ldarg.0 IL_0091: ldfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_009b: ldloca.s V_3 IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00a2: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_00a7: ldc.i4.3 IL_00a8: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00b2: stloc.2 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00ba: brtrue.s IL_00f8 IL_00bc: ldarg.0 IL_00bd: ldc.i4.1 IL_00be: dup IL_00bf: stloc.0 IL_00c0: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldloc.2 IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00cc: ldarg.0 IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d2: ldloca.s V_2 IL_00d4: ldarg.0 IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_00da: leave.s IL_0147 IL_00dc: ldarg.0 IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e2: stloc.2 IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00ef: ldarg.0 IL_00f0: ldc.i4.m1 IL_00f1: dup IL_00f2: stloc.0 IL_00f3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00f8: ldloca.s V_2 IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ff: stloc.1 IL_0100: ldarg.0 IL_0101: ldfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0106: ldarg.0 IL_0107: ldfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_010c: ldloc.1 IL_010d: call ""void Program.<<Main>$>g__Test|0_0(int, string, int)"" IL_0112: ldarg.0 IL_0113: ldnull IL_0114: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_0119: leave.s IL_0134 } catch System.Exception { IL_011b: stloc.s V_4 IL_011d: ldarg.0 IL_011e: ldc.i4.s -2 IL_0120: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0125: ldarg.0 IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_012b: ldloc.s V_4 IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0132: leave.s IL_0147 } IL_0134: ldarg.0 IL_0135: ldc.i4.s -2 IL_0137: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0147: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void DynamicInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 3 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base"" IL_000c: ldstr ""{0}"" IL_0011: ldloc.0 IL_0012: call ""string string.Format(string, object)"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{hole}base""")] [InlineData(@"$""{hole}"" + $""base""")] public void DynamicInHoles_UsesFormat2(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"1base"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: ldstr ""base"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}base"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Fact] public void ImplicitConversionsInConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(object literalLength, object formattedCount) {} } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerAttribute }); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: box ""int"" IL_000c: newobj ""CustomHandler..ctor(object, object)"" IL_0011: pop IL_0012: ret } "); } [Fact] public void MissingCreate_01() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_02() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_03() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5) ); } [Theory] [InlineData(null)] [InlineData("public string ToStringAndClear(int literalLength) => throw null;")] [InlineData("public void ToStringAndClear() => throw null;")] [InlineData("public static string ToStringAndClear() => throw null;")] public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod) { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; " + toStringAndClearMethod + @" public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5) ); } [Fact] public void ObsoleteCreateMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { [System.Obsolete(""Constructor is obsolete"", error: true)] public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5) ); } [Fact] public void ObsoleteAppendLiteralMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; [System.Obsolete(""AppendLiteral is obsolete"", error: true)] public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7) ); } [Fact] public void ObsoleteAppendFormattedMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; [System.Obsolete(""AppendFormatted is obsolete"", error: true)] public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11) ); } private const string UnmanagedCallersOnlyIl = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } }"; [Fact] public void UnmanagedCallersOnlyAppendFormattedMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance void Dispose () cil managed { ldnull throw } .method public hidebysig virtual instance string ToString () cil managed { ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics( // (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7) ); } [Fact] public void UnmanagedCallersOnlyToStringMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance string ToStringAndClear () cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5) ); } [Theory] [InlineData(@"$""{i}{s}""")] [InlineData(@"$""{i}"" + $""{s}""")] public void UnsupportedArgumentType(string expression) { var source = @" unsafe { int* i = null; var s = new S(); _ = " + expression + @"; } ref struct S { }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (6,11): error CS0306: The type 'int*' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11), // (6,14): error CS0306: The type 'S' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length) ); } [Theory] [InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")] [InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")] public void TargetTypedInterpolationHoles(string expression) { var source = @" bool b = true; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2 value: value:"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 81 (0x51) .maxstack 3 .locals init (bool V_0, //b object V_1, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.0 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloc.0 IL_000c: brfalse.s IL_0017 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: stloc.1 IL_0015: br.s IL_0019 IL_0017: ldnull IL_0018: stloc.1 IL_0019: ldloca.s V_2 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0021: ldloca.s V_2 IL_0023: ldloc.0 IL_0024: brfalse.s IL_002e IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: br.s IL_002f IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0034: ldloca.s V_2 IL_0036: ldnull IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_003c: ldloca.s V_2 IL_003e: ldnull IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0044: ldloca.s V_2 IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Theory] [InlineData(@"$""{(null, default)}{new()}""")] [InlineData(@"$""{(null, default)}"" + $""{new()}""")] public void TargetTypedInterpolationHoles_Errors(string expression) { var source = @"System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object' // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29), // (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29), // (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length) ); } [Fact] public void RefTernary() { var source = @" bool b = true; int i = 1; System.Console.WriteLine($""{(!b ? ref i : ref i)}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); } [Fact] public void NestedInterpolatedStrings_01() { var source = @" int i = 1; System.Console.WriteLine($""{$""{i}""}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0013: ldloca.s V_1 IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret } "); } [Theory] [InlineData(@"$""{$""{i1}""}{$""{i2}""}""")] [InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")] public void NestedInterpolatedStrings_02(string expression) { var source = @" int i1 = 1; int i2 = 2; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 63 (0x3f) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldloca.s V_2 IL_0006: ldc.i4.0 IL_0007: ldc.i4.1 IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0015: ldloca.s V_2 IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001c: ldloca.s V_2 IL_001e: ldc.i4.0 IL_001f: ldc.i4.1 IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0025: ldloca.s V_2 IL_0027: ldloc.1 IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_002d: ldloca.s V_2 IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0034: call ""string string.Concat(string, string)"" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: ret } "); } [Fact] public void ExceptionFilter_01() { var source = @" using System; int i = 1; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = i }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{i}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public int Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 .try { IL_0002: ldstr ""Starting try"" IL_0007: call ""void System.Console.WriteLine(string)"" IL_000c: newobj ""MyException..ctor()"" IL_0011: dup IL_0012: ldloc.0 IL_0013: callvirt ""void MyException.Prop.set"" IL_0018: throw } filter { IL_0019: isinst ""MyException"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldc.i4.0 IL_0023: br.s IL_004f IL_0025: callvirt ""string object.ToString()"" IL_002a: ldloca.s V_1 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0033: ldloca.s V_1 IL_0035: ldloc.0 IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_003b: ldloca.s V_1 IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0042: callvirt ""string string.Trim()"" IL_0047: call ""bool string.op_Equality(string, string)"" IL_004c: ldc.i4.0 IL_004d: cgt.un IL_004f: endfilter } // end filter { // handler IL_0051: pop IL_0052: ldstr ""Caught"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: leave.s IL_005e } IL_005e: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ExceptionFilter_02() { var source = @" using System; ReadOnlySpan<char> s = new char[] { 'i' }; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = s.ToString() }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{s}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public string Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: newarr ""char"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 105 IL_000a: stelem.i2 IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])"" IL_0010: stloc.0 .try { IL_0011: ldstr ""Starting try"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: newobj ""MyException..ctor()"" IL_0020: dup IL_0021: ldloca.s V_0 IL_0023: constrained. ""System.ReadOnlySpan<char>"" IL_0029: callvirt ""string object.ToString()"" IL_002e: callvirt ""void MyException.Prop.set"" IL_0033: throw } filter { IL_0034: isinst ""MyException"" IL_0039: dup IL_003a: brtrue.s IL_0040 IL_003c: pop IL_003d: ldc.i4.0 IL_003e: br.s IL_006a IL_0040: callvirt ""string object.ToString()"" IL_0045: ldloca.s V_1 IL_0047: ldc.i4.0 IL_0048: ldc.i4.1 IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0056: ldloca.s V_1 IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005d: callvirt ""string string.Trim()"" IL_0062: call ""bool string.op_Equality(string, string)"" IL_0067: ldc.i4.0 IL_0068: cgt.un IL_006a: endfilter } // end filter { // handler IL_006c: pop IL_006d: ldstr ""Caught"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0079 } IL_0079: ret } "); } [ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] [InlineData(@"$""{s}{c}""")] [InlineData(@"$""{s}"" + $""{c}""")] public void ImplicitUserDefinedConversionInHole(string expression) { var source = @" using System; S s = default; C c = new C(); Console.WriteLine(" + expression + @"); ref struct S { public static implicit operator ReadOnlySpan<char>(S s) => ""S converted""; } class C { public static implicit operator ReadOnlySpan<char>(C s) => ""C converted""; }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:S converted value:C"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, //s C V_1, //c System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: newobj ""C..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.0 IL_0011: ldc.i4.2 IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0024: ldloca.s V_2 IL_0026: ldloc.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)"" IL_002c: ldloca.s V_2 IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ExplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; Console.WriteLine($""{s}""); ref struct S { public static explicit operator ReadOnlySpan<char>(S s) => ""S converted""; } "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,21): error CS0306: The type 'S' may not be used as a type argument // Console.WriteLine($"{s}"); Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ImplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static implicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var verifier = CompileAndVerify(source, expectedOutput: @" literal:Text value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 52 (0x34) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Text"" IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)"" IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.1 IL_001d: box ""int"" IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0027: ldloca.s V_0 IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } "); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ExplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static explicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct' // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void InvalidBuilderReturnType(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public int AppendLiteral(string s) => 0; public int AppendFormatted(object o) => 0; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21), // (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length) ); } [Fact] public void MissingAppendMethods() { var source = @" using System.Runtime.CompilerServices; CustomHandler c = $""Literal{1}""; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } } "; var comp = CreateCompilation(new[] { source, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,21): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 21), // (4,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Literal").WithArguments("?.()").WithLocation(4, 21), // (4,28): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{1}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 28), // (4,28): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("?.()").WithLocation(4, 28) ); } [Fact] public void MissingBoolType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @"CustomHandler c = $""Literal{1}"";"; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyDiagnostics( // (1,19): error CS0518: Predefined type 'System.Boolean' is not defined or imported // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""Literal{1}""").WithArguments("System.Boolean").WithLocation(1, 19) ); } [Fact] public void MissingVoidType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @" class C { public bool M() { CustomHandler c = $""Literal{1}""; return true; } } "; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Void); comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_01(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length) ); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_02(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(string s) { } public bool AppendFormatted(object o) => true; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length) ); } [Fact] public void MixedBuilderReturnTypes_03() { var source = @" using System; Console.WriteLine($""{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { _builder.AppendLine(""value:"" + o.ToString()); } } }"; CompileAndVerify(source, expectedOutput: "value:1"); } [Fact] public void MixedBuilderReturnTypes_04() { var source = @" using System; using System.Text; using System.Runtime.CompilerServices; Console.WriteLine((CustomHandler)$""l""); [InterpolatedStringHandler] public class CustomHandler { private readonly StringBuilder _builder; public CustomHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public override string ToString() => _builder.ToString(); public bool AppendFormatted(object o) => true; public void AppendLiteral(string s) { _builder.AppendLine(""literal:"" + s.ToString()); } } "; CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l"); } private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler") { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var descendentNodes = tree.GetRoot().DescendantNodes(); var interpolatedString = (ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>() .Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any()) .FirstOrDefault() ?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(interpolatedString); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.Exists); Assert.True(semanticInfo.ImplicitConversion.IsValid); Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler); Assert.Null(semanticInfo.ImplicitConversion.Method); if (interpolatedString is BinaryExpressionSyntax) { Assert.False(semanticInfo.ConstantValue.HasValue); AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString()); } // https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings. } private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput) => CompileAndVerify( compilation, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); [Theory] [CombinatorialData] public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns, [CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression) { var code = @" CustomHandler builder = " + expression + @"; System.Console.WriteLine(builder.ToString());"; var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns); var comp = CreateCompilation(new[] { code, builder }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:Literal value:1 alignment:2 format:f"); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (type, useBoolReturns) switch { (type: "struct", useBoolReturns: true) => @" { // Code size 67 (0x43) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""bool CustomHandler.AppendLiteral(string)"" IL_0015: brfalse.s IL_002c IL_0017: ldloca.s V_1 IL_0019: ldc.i4.1 IL_001a: box ""int"" IL_001f: ldc.i4.2 IL_0020: ldstr ""f"" IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: constrained. ""CustomHandler"" IL_0038: callvirt ""string object.ToString()"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } ", (type: "struct", useBoolReturns: false) => @" { // Code size 61 (0x3d) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(string)"" IL_0015: ldloca.s V_1 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldc.i4.2 IL_001e: ldstr ""f"" IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0028: ldloc.1 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""CustomHandler"" IL_0032: callvirt ""string object.ToString()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } ", (type: "class", useBoolReturns: true) => @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""Literal"" IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0013: brfalse.s IL_0029 IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: box ""int"" IL_001c: ldc.i4.2 IL_001d: ldstr ""f"" IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret } ", (type: "class", useBoolReturns: false) => @" { // Code size 47 (0x2f) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldstr ""Literal"" IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: box ""int"" IL_0019: ldc.i4.2 IL_001a: ldstr ""f"" IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret } ", _ => throw ExceptionUtilities.Unreachable }; } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void CustomHandlerMethodArgument(string expression) { var code = @" M(" + expression + @"); void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"($""{1,2:f}"" + $""Literal"")")] public void ExplicitHandlerCast_InCode(string expression) { var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); syntax = ((CastExpressionSyntax)syntax).Expression; Assert.Equal(expression, syntax.ToString()); semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); // https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: call ""void System.Console.WriteLine(object)"" IL_0029: ret } "); } [Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void HandlerConversionPreferredOverStringForNonConstant(string expression) { var code = @" CultureInfoNormalizer.Normalize(); C.M(" + expression + @"); class C { public static void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.7 IL_0006: ldc.i4.1 IL_0007: newobj ""CustomHandler..ctor(int, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldc.i4.2 IL_0015: ldstr ""f"" IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001f: brfalse.s IL_002e IL_0021: ldloc.0 IL_0022: ldstr ""Literal"" IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: pop IL_0030: ldloc.0 IL_0031: call ""void C.M(CustomHandler)"" IL_0036: ret } "); comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9); verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: ldstr ""Literal"" IL_001a: call ""string string.Concat(string, string)"" IL_001f: call ""void C.M(string)"" IL_0024: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}Literal"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: call ""void C.M(string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler b) { throw null; } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Literal"" IL_0005: call ""void C.M(string)"" IL_000a: ret } "); } [Theory] [InlineData(@"$""{1}{2}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type // [Attr($"{1}{2}")] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2) ); VerifyInterpolatedStringExpression(comp); var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); void validate(ModuleSymbol m) { var attr = m.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => throw null; public static void M(CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); comp.VerifyDiagnostics( // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)' // C.M($""); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_01(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_02(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_03(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'. // C.M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_01(string expression) { var code = @" C.M(" + expression + @", default(CustomHandler)); C.M(default(CustomHandler), " + expression + @"); class C { public static void M<T>(T t1, T t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M($"{1,2:f}Literal", default(CustomHandler)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3), // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_02(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), () => $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_03(string expression) { var code = @" using System; C.M(" + expression + @", default(CustomHandler)); class C { public static void M<T>(T t1, T t2) => Console.WriteLine(t1); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 51 (0x33) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ldnull IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)"" IL_0032: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_04(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2()); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_01(string expression) { var code = @" using System; Func<CustomHandler> f = () => " + expression + @"; Console.WriteLine(f()); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_02(string expression) { var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(() => " + expression + @"); class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } "; // Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string, // so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec). var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); // No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldstr ""{0,2:f}Literal"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldstr ""{0,2:f}"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ldstr ""Literal"" IL_0015: call ""string string.Concat(string, string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_03(string expression) { // Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct // when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to // fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>. var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => throw null; public static void M(Func<CustomHandler> f) => Console.WriteLine(f()); } public partial class CustomHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } public ref struct S { public string Field { get; set; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 35 (0x23) .maxstack 4 .locals init (S V_0) IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldloca.s V_0 IL_000a: initobj ""S"" IL_0010: ldloca.s V_0 IL_0012: ldstr ""Field"" IL_0017: call ""void S.Field.set"" IL_001c: ldloc.0 IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)"" IL_0022: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_04(string expression) { // Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type) var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } public partial class CustomHandler { public void AppendFormatted(S value) => throw null; } public ref struct S { public string Field { get; set; } } namespace System.Runtime.CompilerServices { public ref partial struct DefaultInterpolatedStringHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } } "; string[] source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false), GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11), // (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloca.s V_1 IL_000d: initobj ""S"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""Field"" IL_001a: call ""void S.Field.set"" IL_001f: ldloc.1 IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)"" IL_0025: ldloca.s V_0 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_05(string expression) { var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => throw null; public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_06(string expression) { // Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion // means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec) // and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type // has an identity conversion to the return type of Func<bool, string>, that is preferred. var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @" { // Code size 35 (0x23) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ret } " : @" { // Code size 45 (0x2d) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_07(string expression) { // Same as 5, but with an implicit conversion from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } public partial struct CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_08(string expression) { // Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)' // C.M(b => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void LambdaInference_AmbiguousInOlderLangVersions(string expression) { var code = @" using System; C.M(param => { param = " + expression + @"; }); static class C { public static void M(Action<string> f) => throw null; public static void M(Action<CustomHandler> f) => throw null; } "; var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); // This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04 // We should not be changing binding behavior based on LangVersion. comp.VerifyEmitDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)' // C.M(param => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_01(string expression) { var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06 var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 56 (0x38) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_0024 IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: br.s IL_0032 IL_0024: ldloca.s V_0 IL_0026: initobj ""CustomHandler"" IL_002c: ldloc.0 IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } " : @" { // Code size 66 (0x42) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_002e IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: br.s IL_003c IL_002e: ldloca.s V_0 IL_0030: initobj ""CustomHandler"" IL_0036: ldloc.0 IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_03(string expression) { // Same as 02, but with a target-type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_04(string expression) { // Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07 var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_05(string expression) { // Same 01, but with a conversion from string to CustomHandler and CustomHandler to string. var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another // var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_06(string expression) { // Same 05, but with a target type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0046: call ""void System.Console.WriteLine(string)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_01(string expression) { // Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types // and not on expression conversions, no best type can be found for this switch expression. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string. var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 59 (0x3b) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_0034 IL_0023: ldstr ""{0,2:f}Literal"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } " : @" { // Code size 69 (0x45) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_003e IL_0023: ldstr ""{0,2:f}"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: ldstr ""Literal"" IL_0038: call ""string string.Concat(string, string)"" IL_003d: stloc.0 IL_003e: ldloc.0 IL_003f: call ""void System.Console.WriteLine(string)"" IL_0044: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_03(string expression) { // Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile). var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_04(string expression) { // Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: box ""CustomHandler"" IL_0049: call ""void System.Console.WriteLine(object)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_05(string expression) { // Same as 01, but with conversions in both directions. No best common type can be found. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_06(string expression) { // Same as 05, but with a target type. var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_01(string expression) { var code = @" M(" + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(ref CustomHandler)"" IL_002f: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_02(string expression) { var code = @" M(" + expression + @"); M(ref " + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword // M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3), // (3,7): error CS1510: A ref or out value must be an assignable variable // M(ref $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_03(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 5 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_04(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002f: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void RefOverloadResolution_MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => System.Console.WriteLine(c); public static void M(ref CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); VerifyInterpolatedStringExpression(comp, "CustomHandler1"); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler1 V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler1..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler1.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler1)"" IL_002e: ret } "); } private const string InterpolatedStringHandlerAttributesVB = @" Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerAttribute Inherits Attribute End Class <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute Inherits Attribute Public Sub New(argument As String) Arguments = { argument } End Sub Public Sub New(ParamArray arguments() as String) Me.Arguments = arguments End Sub Public ReadOnly Property Arguments As String() End Class End Namespace "; [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (8,27): error CS8946: 'string' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27) ); var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String) End Sub End Class "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); // Note: there is no compilation error here because the natural type of a string is still string, and // we just bind to that method without checking the handler attribute. var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string' // public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70) ); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'. // public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34), // (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; _ = new C(" + expression + @"); class C { public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11), // (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression) { var code = @" using System.Runtime.CompilerServices; C<CustomHandler>.M(" + expression + @"); public class C<T> { public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20), // (8,27): error CS8946: 'T' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27) ); var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C"); var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler"); var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler))); var cParam = substitutedC.GetMethod("M").Parameters.Single(); Assert.IsType<SubstitutedParameterSymbol>(cParam); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C(Of T) Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var goodCode = @" int i = 10; C.M(i: i, c: " + expression + @"); "; var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @" i:10 literal:text "); verifier.VerifyDiagnostics( // (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller // to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); verifyIL(verifier); var badCode = @"C.M(" + expression + @", 1);"; comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'. // C.M($"", 1); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length), // (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller // to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } void verifyIL(CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 36 (0x24) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldloca.s V_2 IL_0007: ldc.i4.4 IL_0008: ldc.i4.0 IL_0009: ldloc.0 IL_000a: call ""CustomHandler..ctor(int, int, int)"" IL_000f: ldloca.s V_2 IL_0011: ldstr ""text"" IL_0016: call ""bool CustomHandler.AppendLiteral(string)"" IL_001b: pop IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call ""void C.M(CustomHandler, int)"" IL_0023: ret } " : @" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldc.i4.4 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_3 IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000f: stloc.2 IL_0010: ldloc.3 IL_0011: brfalse.s IL_0021 IL_0013: ldloca.s V_2 IL_0015: ldstr ""text"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.2 IL_0024: ldloc.1 IL_0025: call ""void C.M(CustomHandler, int)"" IL_002a: ret } "); } } [Fact] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { private CustomHandler(int literalLength, int formattedCount, int i) : this() {} static void InCustomHandler() { C.M(1, " + expression + @"); } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() }); comp.VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8) ); comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics) { var code = @" using System.Runtime.CompilerServices; int i = 0; C.M(" + mRef + @" i, " + expression + @"); public class C { public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression, // (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6)); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this() { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var expectedDiagnostics = extraConstructorArg == "" ? new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5) } : new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)' // C.M(1, $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8) }; var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { comp = CreateCompilation(executableCode, new[] { d }); comp.VerifyDiagnostics(expectedDiagnostics); } static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString(); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" using System; int i = 10; Console.WriteLine(C.M(i, " + expression + @")); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 39 (0x27) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.1 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""CustomHandler..ctor(int, int, int)"" IL_000e: ldloca.s V_1 IL_0010: ldstr ""2"" IL_0015: call ""bool CustomHandler.AppendLiteral(string)"" IL_001a: pop IL_001b: ldloc.1 IL_001c: call ""string C.M(int, CustomHandler)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } " : @" { // Code size 46 (0x2e) .maxstack 5 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: ldloc.0 IL_0007: ldloca.s V_2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0020 IL_0012: ldloca.s V_1 IL_0014: ldstr ""2"" IL_0019: call ""bool CustomHandler.AppendLiteral(string)"" IL_001e: br.s IL_0021 IL_0020: ldc.i4.0 IL_0021: pop IL_0022: ldloc.1 IL_0023: call ""string C.M(int, CustomHandler)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" int i = 10; string s = ""arg""; C.M(i, s, " + expression + @"); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); string expectedOutput = @" i:10 s:arg literal:literal "; var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol verifier) { var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 44 (0x2c) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldloca.s V_3 IL_000f: ldc.i4.7 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloc.2 IL_0013: call ""CustomHandler..ctor(int, int, int, string)"" IL_0018: ldloca.s V_3 IL_001a: ldstr ""literal"" IL_001f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0024: pop IL_0025: ldloc.3 IL_0026: call ""void C.M(int, string, CustomHandler)"" IL_002b: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldc.i4.7 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: ldloc.2 IL_0011: ldloca.s V_4 IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_0018: stloc.3 IL_0019: ldloc.s V_4 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_3 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.3 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; string s = null; object o; C.M(i, ref s, out o, " + expression + @"); Console.WriteLine(s); Console.WriteLine(o); public class C { public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c) { Console.WriteLine(s); o = ""o in M""; s = ""s in M""; Console.Write(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount) { o = null; s = ""s in constructor""; _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" s in constructor i:1 literal:literal s in M o in M "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 67 (0x43) .maxstack 8 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)"" IL_0020: stloc.s V_6 IL_0022: ldloca.s V_6 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: pop IL_002f: ldloc.s V_6 IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_0036: ldloc.1 IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldloc.2 IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: ret } " : @" { // Code size 76 (0x4c) .maxstack 9 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6, bool V_7) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: ldloca.s V_7 IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)"" IL_0022: stloc.s V_6 IL_0024: ldloc.s V_7 IL_0026: brfalse.s IL_0036 IL_0028: ldloca.s V_6 IL_002a: ldstr ""literal"" IL_002f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0034: br.s IL_0037 IL_0036: ldc.i4.0 IL_0037: pop IL_0038: ldloc.s V_6 IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_003f: ldloc.1 IL_0040: call ""void System.Console.WriteLine(string)"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), GetString(), " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt GetString s:str i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 45 (0x2d) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: call ""CustomHandler..ctor(int, int, string, int)"" IL_0019: ldloca.s V_2 IL_001b: ldstr ""literal"" IL_0020: call ""bool CustomHandler.AppendLiteral(string)"" IL_0025: pop IL_0026: ldloc.2 IL_0027: call ""void C.M(int, string, CustomHandler)"" IL_002c: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_3 IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)"" IL_0019: stloc.2 IL_001a: ldloc.3 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_2 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.2 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetC().M(s: GetString(), i: GetInt(), c: " + expression + @"); C GetC() { Console.WriteLine(""GetC""); return new C { Field = 5 }; } int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public int Field; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""c.Field:"" + c.Field.ToString()); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetC GetString GetInt s:str c.Field:5 i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 56 (0x38) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldloca.s V_4 IL_0019: ldc.i4.7 IL_001a: ldc.i4.0 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldloc.2 IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)"" IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""bool CustomHandler.AppendLiteral(string)"" IL_002f: pop IL_0030: ldloc.s V_4 IL_0032: callvirt ""void C.M(int, string, CustomHandler)"" IL_0037: ret } " : @" { // Code size 65 (0x41) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4, bool V_5) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldc.i4.7 IL_0018: ldc.i4.0 IL_0019: ldloc.0 IL_001a: ldloc.1 IL_001b: ldloc.2 IL_001c: ldloca.s V_5 IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)"" IL_0023: stloc.s V_4 IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0037 IL_0029: ldloca.s V_4 IL_002b: ldstr ""literal"" IL_0030: call ""bool CustomHandler.AppendLiteral(string)"" IL_0035: br.s IL_0038 IL_0037: ldc.i4.0 IL_0038: pop IL_0039: ldloc.s V_4 IL_003b: callvirt ""void C.M(int, string, CustomHandler)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), """", " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""i2:"" + i2.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt i1:10 i2:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 43 (0x2b) .maxstack 7 .locals init (int V_0, CustomHandler V_1) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: call ""CustomHandler..ctor(int, int, int, int)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: call ""void C.M(int, string, CustomHandler)"" IL_002a: ret } " : @" { // Code size 50 (0x32) .maxstack 7 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldc.i4.7 IL_000d: ldc.i4.0 IL_000e: ldloc.0 IL_000f: ldloc.0 IL_0010: ldloca.s V_2 IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: brfalse.s IL_0029 IL_001b: ldloca.s V_1 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.1 IL_002c: call ""void C.M(int, string, CustomHandler)"" IL_0031: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, """", " + expression + @"); public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: newobj ""CustomHandler..ctor(int, int)"" IL_000d: call ""void C.M(int, string, CustomHandler)"" IL_0012: ret } " : @" { // Code size 21 (0x15) .maxstack 5 .locals init (bool V_0) IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)"" IL_000f: call ""void C.M(int, string, CustomHandler)"" IL_0014: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { } } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics( (extraConstructorArg == "") ? new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12), // (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12) } : new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12), // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12) } ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); Console.WriteLine(c[10, ""str"", " + expression + @"]); public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: callvirt ""string C.this[int, string, CustomHandler].get"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""string C.this[int, string, CustomHandler].get"" IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); c[10, ""str"", " + expression + @"] = """"; public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: ldstr """" IL_002e: callvirt ""void C.this[int, string, CustomHandler].set"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: ldstr """" IL_0035: callvirt ""void C.this[int, string, CustomHandler].set"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; (new C(5)).M((int)10, ""str"", " + expression + @"); public class C { public int Prop { get; } public C(int i) => Prop = i; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""c.Prop:"" + c.Prop.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 c.Prop:5 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 51 (0x33) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_3 IL_0015: ldc.i4.7 IL_0016: ldc.i4.0 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)"" IL_001f: ldloca.s V_3 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: pop IL_002c: ldloc.3 IL_002d: callvirt ""void C.M(int, string, CustomHandler)"" IL_0032: ret } " : @" { // Code size 59 (0x3b) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: ldloc.1 IL_0017: ldloc.2 IL_0018: ldloca.s V_4 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)"" IL_001f: stloc.3 IL_0020: ldloc.s V_4 IL_0022: brfalse.s IL_0032 IL_0024: ldloca.s V_3 IL_0026: ldstr ""literal"" IL_002b: call ""bool CustomHandler.AppendLiteral(string)"" IL_0030: br.s IL_0033 IL_0032: ldc.i4.0 IL_0033: pop IL_0034: ldloc.3 IL_0035: callvirt ""void C.M(int, string, CustomHandler)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(5, " + expression + @"); public class C { public int Prop { get; } public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" i:5 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 34 (0x22) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldloca.s V_1 IL_0005: ldc.i4.7 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: call ""CustomHandler..ctor(int, int, int)"" IL_000d: ldloca.s V_1 IL_000f: ldstr ""literal"" IL_0014: call ""bool CustomHandler.AppendLiteral(string)"" IL_0019: pop IL_001a: ldloc.1 IL_001b: newobj ""C..ctor(int, CustomHandler)"" IL_0020: pop IL_0021: ret } "); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_Success([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: callvirt ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_Success_StructReceiver([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public struct C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: call ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: call ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC().M(" + expression + @"); " + refness + @" C GetC() => throw null; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC().M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10) ); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); ref C GetC(ref C c) => ref c; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "ref").WithLocation(5, 15) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Rvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(s2, " + expression + @"); public struct S { public int I; public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" s1.I:1 s2.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 6 .locals init (S V_0, //s2 S V_1, S V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: ldloca.s V_1 IL_0013: initobj ""S"" IL_0019: ldloca.s V_1 IL_001b: ldc.i4.2 IL_001c: stfld ""int S.I"" IL_0021: ldloc.1 IL_0022: stloc.0 IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldloc.1 IL_002c: ldloc.2 IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)"" IL_0032: call ""void S.M(S, CustomHandler)"" IL_0037: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Lvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(ref s2, " + expression + @"); public struct S { public int I; public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword // s1.M(ref s2, $""); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByVal(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(s, " + expression + @"); public struct S { public int I; public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.0 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: newobj ""CustomHandler..ctor(int, int, S)"" IL_001b: call ""void S.M(S, CustomHandler)"" IL_0020: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByRef(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(ref s, " + expression + @"); public struct S { public int I; public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 36 (0x24) .maxstack 4 .locals init (S V_0, //s S V_1, S& V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldc.i4.0 IL_0017: ldc.i4.0 IL_0018: ldloc.2 IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)"" IL_001e: call ""void S.M(ref S, CustomHandler)"" IL_0023: ret } "); } [Theory] [CombinatorialData] public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetReceiver().M( GetArg(""Unrelated parameter 1""), GetArg(""Second value""), GetArg(""Unrelated parameter 2""), GetArg(""First value""), " + expression + @", GetArg(""Unrelated parameter 4"")); C GetReceiver() { Console.WriteLine(""GetReceiver""); return new C() { Prop = ""Prop"" }; } string GetArg(string s) { Console.WriteLine(s); return s; } public class C { public string Prop { get; set; } public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""s1:"" + s1); _builder.AppendLine(""c.Prop:"" + c.Prop); _builder.AppendLine(""s2:"" + s2); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @" GetReceiver Unrelated parameter 1 Second value Unrelated parameter 2 First value Handler constructor Unrelated parameter 4 s1:First value c.Prop:Prop s2:Second value literal:literal "); verifier.VerifyDiagnostics(); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$""literal"" + $""""")] public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression) { var code = @" using System; using System.Globalization; using System.Runtime.CompilerServices; int i = 1; C.M(i, " + expression + @"); public class C { public static implicit operator C(int i) => throw null; public static implicit operator C(double d) { Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture)); return new C(); } public override string ToString() => ""C""; public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" 1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 39 (0x27) .maxstack 5 .locals init (double V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: conv.r8 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.7 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""C C.op_Implicit(double)"" IL_000e: call ""CustomHandler..ctor(int, int, C)"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""literal"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: pop IL_0020: ldloc.1 IL_0021: call ""void C.M(double, CustomHandler)"" IL_0026: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { public int Prop { get; set; } public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); return 0; } set { Console.WriteLine(""Indexer setter""); Console.WriteLine(c.ToString()); } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter GetInt2 Indexer setter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 85 (0x55) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.s V_5 IL_0039: stloc.s V_4 IL_003b: ldloc.2 IL_003c: ldloc.3 IL_003d: ldloc.s V_4 IL_003f: ldloc.2 IL_0040: ldloc.3 IL_0041: ldloc.s V_4 IL_0043: callvirt ""int C.this[int, CustomHandler].get"" IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: callvirt ""void C.this[int, CustomHandler].set"" IL_0054: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 95 (0x5f) .maxstack 6 .locals init (int V_0, //i CustomHandler V_1, bool V_2, int V_3, C V_4, int V_5, CustomHandler V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.s V_4 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.3 IL_0010: ldloc.3 IL_0011: stloc.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.3 IL_0016: ldloc.s V_4 IL_0018: ldloca.s V_2 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001f: stloc.1 IL_0020: ldloc.2 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_1 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.1 IL_003f: stloc.s V_6 IL_0041: ldloc.s V_4 IL_0043: ldloc.s V_5 IL_0045: ldloc.s V_6 IL_0047: ldloc.s V_4 IL_0049: ldloc.s V_5 IL_004b: ldloc.s V_6 IL_004d: callvirt ""int C.this[int, CustomHandler].get"" IL_0052: ldc.i4.2 IL_0053: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0058: add IL_0059: callvirt ""void C.this[int, CustomHandler].set"" IL_005e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 91 (0x5b) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_5 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.s V_5 IL_003f: stloc.s V_4 IL_0041: ldloc.2 IL_0042: ldloc.3 IL_0043: ldloc.s V_4 IL_0045: ldloc.2 IL_0046: ldloc.3 IL_0047: ldloc.s V_4 IL_0049: callvirt ""int C.this[int, CustomHandler].get"" IL_004e: ldc.i4.2 IL_004f: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0054: add IL_0055: callvirt ""void C.this[int, CustomHandler].set"" IL_005a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 97 (0x61) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0041 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: brfalse.s IL_0041 IL_0030: ldloca.s V_5 IL_0032: ldloc.0 IL_0033: box ""int"" IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003f: br.s IL_0042 IL_0041: ldc.i4.0 IL_0042: pop IL_0043: ldloc.s V_5 IL_0045: stloc.s V_4 IL_0047: ldloc.2 IL_0048: ldloc.3 IL_0049: ldloc.s V_4 IL_004b: ldloc.2 IL_004c: ldloc.3 IL_004d: ldloc.s V_4 IL_004f: callvirt ""int C.this[int, CustomHandler].get"" IL_0054: ldc.i4.2 IL_0055: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_005a: add IL_005b: callvirt ""void C.this[int, CustomHandler].set"" IL_0060: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); Console.WriteLine(c.ToString()); return ref field; } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.this[int, CustomHandler].get"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 81 (0x51) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: stloc.3 IL_0012: ldc.i4.7 IL_0013: ldc.i4.1 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: ldloca.s V_5 IL_0018: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001d: stloc.s V_4 IL_001f: ldloc.s V_5 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_4 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.3 IL_003f: ldloc.s V_4 IL_0041: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0046: dup IL_0047: ldind.i4 IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: stind.i4 IL_0050: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC().M(GetInt(1), " + expression + @") += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c) { Console.WriteLine(""M""); Console.WriteLine(c.ToString()); return ref field; } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor M arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.M(int, CustomHandler)"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 81 (0x51) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: stloc.3 IL_0012: ldc.i4.7 IL_0013: ldc.i4.1 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: ldloca.s V_5 IL_0018: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001d: stloc.s V_4 IL_001f: ldloc.s V_5 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_4 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.3 IL_003f: ldloc.s V_4 IL_0041: callvirt ""ref int C.M(int, CustomHandler)"" IL_0046: dup IL_0047: ldind.i4 IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: stind.i4 IL_0050: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.M(int, CustomHandler)"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.M(int, CustomHandler)"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression) { var code = @" using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; _ = new C(1) { " + expression + @" }; public class C : IEnumerable<int> { public int Field; public C(int i) { Field = i; } public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c) { Console.WriteLine(c.ToString()); } public IEnumerator<int> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => throw null; } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 5 .locals init (C V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_1 IL_000a: ldc.i4.7 IL_000b: ldc.i4.0 IL_000c: ldloc.0 IL_000d: call ""CustomHandler..ctor(int, int, C)"" IL_0012: ldloca.s V_1 IL_0014: ldstr ""literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: callvirt ""void C.Add(CustomHandler)"" IL_0024: ret } "); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_DictionaryInitializer(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(1) { [" + expression + @"] = 1 }; public class C { public int Field; public C(int i) { Field = i; } public int this[[InterpolatedStringHandlerArgument("""")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 40 (0x28) .maxstack 4 .locals init (C V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_2 IL_0009: ldc.i4.7 IL_000a: ldc.i4.0 IL_000b: ldloc.0 IL_000c: call ""CustomHandler..ctor(int, int, C)"" IL_0011: ldloca.s V_2 IL_0013: ldstr ""literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloc.2 IL_001e: stloc.1 IL_001f: ldloc.0 IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: callvirt ""void C.this[CustomHandler].set"" IL_0027: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler) { Console.WriteLine(handler.ToString()); } } public partial class CustomHandler { private int I = 0; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""int constructor""); I = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""CustomHandler constructor""); _builder.AppendLine(""c.I:"" + c.I.ToString()); " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c) { _builder.AppendLine(""CustomHandler AppendFormatted""); _builder.Append(c.ToString()); " + (useBoolReturns ? "return true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" int constructor CustomHandler constructor CustomHandler AppendFormatted c.I:1 literal:Inner string value:2 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 59 (0x3b) .maxstack 6 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: dup IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: ldc.i4.s 12 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0017: dup IL_0018: ldstr ""Inner string"" IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: box ""int"" IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: call ""void C.M(int, CustomHandler)"" IL_003a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 77 (0x4d) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_0046 IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0031 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0031: ldloc.s V_4 IL_0033: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0038: ldloc.1 IL_0039: ldc.i4.2 IL_003a: box ""int"" IL_003f: ldc.i4.0 IL_0040: ldnull IL_0041: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0046: ldloc.1 IL_0047: call ""void C.M(int, CustomHandler)"" IL_004c: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 68 (0x44) .maxstack 5 .locals init (int V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldc.i4.s 12 IL_0011: ldc.i4.0 IL_0012: ldloc.2 IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0018: dup IL_0019: ldstr ""Inner string"" IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_0029: brfalse.s IL_003b IL_002b: ldloc.1 IL_002c: ldc.i4.2 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.1 IL_003e: call ""void C.M(int, CustomHandler)"" IL_0043: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0033 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ldloc.s V_4 IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_003c: brfalse.s IL_004e IL_003e: ldloc.1 IL_003f: ldc.i4.2 IL_0040: box ""int"" IL_0045: ldc.i4.0 IL_0046: ldnull IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void DiscardsUsedAsParameters(string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(out _, " + expression + @"); public class C { public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) { i = 0; Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount) { i = 1; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 4 .locals init (int V_0, CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: ldstr ""literal"" IL_0013: call ""void CustomHandler.AppendLiteral(string)"" IL_0018: ldloc.1 IL_0019: call ""void C.M(out int, CustomHandler)"" IL_001e: ret } "); } [Fact] public void DiscardsUsedAsParameters_DefinedInVB() { var vb = @" Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler) Console.WriteLine(i) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer) i = 1 End Sub End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @"C.M(out _, $"""");"; var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() }); var verifier = CompileAndVerify(comp, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: call ""void C.M(out int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DisallowedInExpressionTrees(string expression) { var code = @" using System; using System.Linq.Expressions; Expression<Func<CustomHandler>> expr = () => " + expression + @"; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler }); comp.VerifyDiagnostics( // (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion. // Expression<Func<CustomHandler>> expr = () => $""; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46) ); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_01() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_02() { var code = @" using System.Linq.Expressions; Expression e = (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_03() { var code = @" using System; using System.Linq.Expressions; Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_04() { var code = @" using System; using System.Linq.Expressions; Expression e = Func<string, string> () => (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_05() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 167 (0xa7) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldstr ""literal"" IL_0073: ldtoken ""string"" IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0082: ldtoken ""string string.Concat(string, string)"" IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_008c: castclass ""System.Reflection.MethodInfo"" IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0096: ldc.i4.1 IL_0097: newarr ""System.Linq.Expressions.ParameterExpression"" IL_009c: dup IL_009d: ldc.i4.0 IL_009e: ldloc.0 IL_009f: stelem.ref IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a5: pop IL_00a6: ret } "); } [Theory] [CombinatorialData] public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @", " + expression + @"); public class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString()); } public partial class CustomHandler { private int i; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); this.i = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""c.i:"" + c.i.ToString()); " + (validityParameter ? "success = true;" : "") + @" } }"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", }; } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsFormattableString() { var code = @" M($""{1}"" + $""literal""); System.FormattableString s = $""{1}"" + $""literal""; void M(System.FormattableString s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.FormattableString' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.FormattableString").WithLocation(2, 3), // (3,30): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString' // System.FormattableString s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.FormattableString").WithLocation(3, 30) ); } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsIFormattable() { var code = @" M($""{1}"" + $""literal""); System.IFormattable s = $""{1}"" + $""literal""; void M(System.IFormattable s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.IFormattable' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.IFormattable").WithLocation(2, 3), // (3,25): error CS0029: Cannot implicitly convert type 'string' to 'System.IFormattable' // System.IFormattable s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.IFormattable").WithLocation(3, 25) ); } [Theory] [CombinatorialData] public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression) { var code = @" int i; string s; CustomHandler c = " + expression + @"; _ = i.ToString(); _ = o.ToString(); _ = s.ToString(); string M(out object o) { o = null; return null; } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (6,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5), // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else if (useBoolReturns) { comp.VerifyDiagnostics( // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression) { var code = @" int i; CustomHandler c = " + expression + @"; _ = i.ToString(); "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (5,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_01(string expression) { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_02(string expression) { var code = @" using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount) { Console.WriteLine(""d:"" + d.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "d:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: box ""int"" IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)"" IL_0010: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0015: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(dynamic literalLength, int formattedCount) { Console.WriteLine(""ctor""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: newobj ""CustomHandler..ctor(dynamic, int)"" IL_000c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0011: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { Console.WriteLine(""ctor""); } public CustomHandler(dynamic literalLength, int formattedCount) { throw null; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_000c: ret } "); } [Theory] [InlineData(@"$""Literal""")] [InlineData(@"$"""" + $""Literal""")] public void DynamicConstruction_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_0015: ldloc.0 IL_0016: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001b: ret } "); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""""")] public void DynamicConstruction_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 29 (0x1d) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)"" IL_0016: ldloc.0 IL_0017: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001c: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_08(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 128 (0x80) .maxstack 9 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0021: brtrue.s IL_0062 IL_0023: ldc.i4 0x100 IL_0028: ldstr ""AppendFormatted"" IL_002d: ldnull IL_002e: ldtoken ""Program"" IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0038: ldc.i4.2 IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003e: dup IL_003f: ldc.i4.0 IL_0040: ldc.i4.s 9 IL_0042: ldnull IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldc.i4.0 IL_004c: ldnull IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0052: stelem.ref IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target"" IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0071: ldloca.s V_1 IL_0073: ldloc.0 IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_0079: ldloc.1 IL_007a: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_007f: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_09(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public bool AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); return true; } public bool AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); return true; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 196 (0xc4) .maxstack 11 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)"" IL_001c: brfalse IL_00bb IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0026: brtrue.s IL_004c IL_0028: ldc.i4.0 IL_0029: ldtoken ""bool"" IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0033: ldtoken ""Program"" IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_0060: brtrue.s IL_009d IL_0062: ldc.i4.0 IL_0063: ldstr ""AppendFormatted"" IL_0068: ldnull IL_0069: ldtoken ""Program"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.2 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.s 9 IL_007d: ldnull IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0083: stelem.ref IL_0084: dup IL_0085: ldc.i4.1 IL_0086: ldc.i4.0 IL_0087: ldnull IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008d: stelem.ref IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00ac: ldloca.s V_1 IL_00ae: ldloc.0 IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00b9: br.s IL_00bc IL_00bb: ldc.i4.0 IL_00bc: pop IL_00bd: ldloc.1 IL_00be: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_00c3: ret } "); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_01(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // return $"{s}"; Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_02(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8150: By-value returns may only be used in methods that return by value // return $"{s}"; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return ref " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // return ref $"{s}"; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { S1 s1; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; } public void AppendFormatted(Span<char> s) => this.s1.s = s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s1, " + expression + @"); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9), // (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23) ); } [Theory] [InlineData(@"$""{s1}""")] [InlineData(@"$""{s1}"" + $""""")] public void RefEscape_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public void AppendFormatted(S1 s1) => s1.s = this.s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s, " + expression + @"); } public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_08() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public static CustomHandler M() { Span<char> s = stackalloc char[10]; ref CustomHandler c = ref M2(ref s, $""""); return c; } public static ref CustomHandler M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] ref CustomHandler handler) { return ref handler; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (16,16): error CS8352: Cannot use local 'c' in this context because it may expose referenced variables outside of their declaration scope // return c; Diagnostic(ErrorCode.ERR_EscapeLocal, "c").WithArguments("c").WithLocation(16, 16) ); } [Fact] public void RefEscape_09() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { s1.Handler = this; } public static void M(ref S1 s1) { Span<char> s2 = stackalloc char[10]; M2(ref s1, $""{s2}""); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler handler) { } public void AppendFormatted(Span<char> s) { this.s = s; } } public ref struct S1 { public CustomHandler Handler; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (15,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s2}"")").WithArguments("CustomHandler.M2(ref S1, CustomHandler)", "handler").WithLocation(15, 9), // (15,23): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(15, 23) ); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_01(string expression) { var code = @" int i = 1; System.Console.WriteLine(" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" { value:1 }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""{ "" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldstr "" }"" IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_002b: ldloca.s V_1 IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_02(string expression) { var code = @" int i = 1; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:{ value:1 alignment:0 format: literal: }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 71 (0x47) .maxstack 4 .locals init (int V_0, //i CustomHandler V_1, //c CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_2 IL_000d: ldstr ""{ "" IL_0012: call ""void CustomHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0026: ldloca.s V_2 IL_0028: ldstr "" }"" IL_002d: call ""void CustomHandler.AppendLiteral(string)"" IL_0032: ldloc.2 IL_0033: stloc.1 IL_0034: ldloca.s V_1 IL_0036: constrained. ""CustomHandler"" IL_003c: callvirt ""string object.ToString()"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ret } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 value:2 value:3 4 "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 66 (0x42) .maxstack 3 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 int V_3, //i4 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldc.i4.4 IL_0007: stloc.3 IL_0008: ldloca.s V_4 IL_000a: ldc.i4.0 IL_000b: ldc.i4.3 IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0011: ldloca.s V_4 IL_0013: ldloc.0 IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0019: ldloca.s V_4 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: ldloca.s V_4 IL_0023: ldloc.2 IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0029: ldloca.s V_4 IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0030: ldloca.s V_3 IL_0032: call ""string int.ToString()"" IL_0037: call ""string string.Concat(string, string)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""({i1}),"" + $""[{i2}],"" + $""{{{i3}}}""")] [InlineData(@"($""({i1}),"" + $""[{i2}],"") + $""{{{i3}}}""")] [InlineData(@"$""({i1}),"" + ($""[{i2}],"" + $""{{{i3}}}"")")] public void InterpolatedStringsAddedUnderObjectAddition2(string expression) { var code = $@" int i1 = 1; int i2 = 2; int i3 = 3; System.Console.WriteLine({expression});"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: @" ( value:1 ), [ value:2 ], { value:3 } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition3() { var code = @" #nullable enable using System; try { var s = string.Empty; Console.WriteLine($""{s = null}{s.Length}"" + $""""); } catch (NullReferenceException) { Console.WriteLine(""Null reference exception caught.""); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: "Null reference exception caught.").VerifyIL("<top-level-statements-entry-point>", @" { // Code size 65 (0x41) .maxstack 3 .locals init (string V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) .try { IL_0000: ldsfld ""string string.Empty"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: ldc.i4.2 IL_0008: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldnull IL_0011: dup IL_0012: stloc.0 IL_0013: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0018: ldloca.s V_1 IL_001a: ldloc.0 IL_001b: callvirt ""int string.Length.get"" IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: ldloca.s V_1 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: call ""void System.Console.WriteLine(string)"" IL_0031: leave.s IL_0040 } catch System.NullReferenceException { IL_0033: pop IL_0034: ldstr ""Null reference exception caught."" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: leave.s IL_0040 } IL_0040: ret } ").VerifyDiagnostics( // (9,36): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine($"{s = null}{s.Length}" + $""); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 36) ); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" object o1; object o2; object o3; _ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1; o1.ToString(); o2.ToString(); o3.ToString(); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); comp.VerifyDiagnostics( // (7,1): error CS0165: Use of unassigned local variable 'o2' // o2.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1), // (8,1): error CS0165: Use of unassigned local variable 'o3' // o3.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1) ); } [Fact] public void ParenthesizedAdditiveExpression_01() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = ($""{i1}"" + $""{i2}"") + $""{i3}""; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 82 (0x52) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 CustomHandler V_3, //c CustomHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldloca.s V_4 IL_0008: ldc.i4.0 IL_0009: ldc.i4.3 IL_000a: call ""CustomHandler..ctor(int, int)"" IL_000f: ldloca.s V_4 IL_0011: ldloc.0 IL_0012: box ""int"" IL_0017: ldc.i4.0 IL_0018: ldnull IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001e: ldloca.s V_4 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002d: ldloca.s V_4 IL_002f: ldloc.2 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldloc.s V_4 IL_003e: stloc.3 IL_003f: ldloca.s V_3 IL_0041: constrained. ""CustomHandler"" IL_0047: callvirt ""string object.ToString()"" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_02() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = $""{i1}"" + ($""{i2}"" + $""{i3}""); System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler c = $"{i1}" + ($"{i2}" + $"{i3}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{i1}"" + ($""{i2}"" + $""{i3}"")").WithArguments("string", "CustomHandler").WithLocation(6, 19) ); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_01(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) = (" + initializer + @"); System.Console.Write(c1.ToString()); System.Console.WriteLine(c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 91 (0x5b) .maxstack 4 .locals init (CustomHandler V_0, //c1 CustomHandler V_1, //c2 CustomHandler V_2, CustomHandler V_3) IL_0000: ldloca.s V_3 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_3 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.0 IL_0012: ldnull IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0018: ldloc.3 IL_0019: stloc.2 IL_001a: ldloca.s V_3 IL_001c: ldc.i4.0 IL_001d: ldc.i4.1 IL_001e: call ""CustomHandler..ctor(int, int)"" IL_0023: ldloca.s V_3 IL_0025: ldc.i4.2 IL_0026: box ""int"" IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0032: ldloc.3 IL_0033: ldloc.2 IL_0034: stloc.0 IL_0035: stloc.1 IL_0036: ldloca.s V_0 IL_0038: constrained. ""CustomHandler"" IL_003e: callvirt ""string object.ToString()"" IL_0043: call ""void System.Console.Write(string)"" IL_0048: ldloca.s V_1 IL_004a: constrained. ""CustomHandler"" IL_0050: callvirt ""string object.ToString()"" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ret } "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_02(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) t = (" + initializer + @"); System.Console.Write(t.c1.ToString()); System.Console.WriteLine(t.c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 104 (0x68) .maxstack 6 .locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldc.i4.1 IL_000e: box ""int"" IL_0013: ldc.i4.0 IL_0014: ldnull IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001a: ldloc.1 IL_001b: ldloca.s V_1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.1 IL_001f: call ""CustomHandler..ctor(int, int)"" IL_0024: ldloca.s V_1 IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0033: ldloc.1 IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)"" IL_0039: ldloca.s V_0 IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1"" IL_0040: constrained. ""CustomHandler"" IL_0046: callvirt ""string object.ToString()"" IL_004b: call ""void System.Console.Write(string)"" IL_0050: ldloca.s V_0 IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2"" IL_0057: constrained. ""CustomHandler"" IL_005d: callvirt ""string object.ToString()"" IL_0062: call ""void System.Console.WriteLine(string)"" IL_0067: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{h1}{h2}""")] [InlineData(@"$""{h1}"" + $""{h2}""")] public void RefStructHandler_DynamicInHole(string expression) { var code = @" dynamic h1 = 1; dynamic h2 = 2; CustomHandler c = " + expression + ";"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "ref struct", useBoolReturns: false); var comp = CreateCompilationWithCSharp(new[] { code, handler }); // Note: We don't give any errors when mixing dynamic and ref structs today. If that ever changes, we should get an // error here. This will crash at runtime because of this. comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Literal{1}""")] [InlineData(@"$""Literal"" + $""{1}""")] public void ConversionInParamsArguments(string expression) { var code = @" using System; using System.Linq; M(" + expression + ", " + expression + @"); void M(params CustomHandler[] handlers) { Console.WriteLine(string.Join(Environment.NewLine, handlers.Select(h => h.ToString()))); } "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, expectedOutput: @" literal:Literal value:1 alignment:0 format: literal:Literal value:1 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 100 (0x64) .maxstack 7 .locals init (CustomHandler V_0) IL_0000: ldc.i4.2 IL_0001: newarr ""CustomHandler"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: ldc.i4.7 IL_000b: ldc.i4.1 IL_000c: call ""CustomHandler..ctor(int, int)"" IL_0011: ldloca.s V_0 IL_0013: ldstr ""Literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloca.s V_0 IL_001f: ldc.i4.1 IL_0020: box ""int"" IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002c: ldloc.0 IL_002d: stelem ""CustomHandler"" IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldloca.s V_0 IL_0036: ldc.i4.7 IL_0037: ldc.i4.1 IL_0038: call ""CustomHandler..ctor(int, int)"" IL_003d: ldloca.s V_0 IL_003f: ldstr ""Literal"" IL_0044: call ""void CustomHandler.AppendLiteral(string)"" IL_0049: ldloca.s V_0 IL_004b: ldc.i4.1 IL_004c: box ""int"" IL_0051: ldc.i4.0 IL_0052: ldnull IL_0053: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0058: ldloc.0 IL_0059: stelem ""CustomHandler"" IL_005e: call ""void Program.<<Main>$>g__M|0_0(CustomHandler[])"" IL_0063: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_01(string mod) { var code = @" using System.Runtime.CompilerServices; M($""""); " + mod + @" void M([InterpolatedStringHandlerArgument("""")] CustomHandler c) { } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (6,10): error CS8944: 'M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // void M([InterpolatedStringHandlerArgument("")] CustomHandler c) { } Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M(CustomHandler)").WithLocation(6, 10 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; M(1, $""""); " + mod + @" void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_01(string mod) { var code = @" using System.Runtime.CompilerServices; var a = " + mod + @" ([InterpolatedStringHandlerArgument("""")] CustomHandler c) => { }; a($""""); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,12): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument("""")").WithLocation(4, 12 + mod.Length), // (4,12): error CS8944: 'lambda expression' is not an instance method, the receiver cannot be an interpolated string handler argument. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("lambda expression").WithLocation(4, 12 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; var a = " + mod + @" (int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); a(1, $""""); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) => throw null; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @""); verifier.VerifyDiagnostics( // (5,19): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = (int i, [InterpolatedStringHandlerArgument("i")] CustomHandler c) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument(""i"")").WithLocation(5, 19 + mod.Length) ); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 4 IL_0000: ldsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""System.Action<int, CustomHandler>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: newobj ""CustomHandler..ctor(int, int)"" IL_0027: callvirt ""void System.Action<int, CustomHandler>.Invoke(int, CustomHandler)"" IL_002c: ret } "); } [Fact] public void ArgumentsOnDelegateTypes_01() { var code = @" using System.Runtime.CompilerServices; M m = null; m($""""); delegate void M([InterpolatedStringHandlerArgument("""")] CustomHandler c); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(6, 3), // (8,18): error CS8944: 'M.Invoke(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // delegate void M([InterpolatedStringHandlerArgument("")] CustomHandler c); Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M.Invoke(CustomHandler)").WithLocation(8, 18) ); } [Fact] public void ArgumentsOnDelegateTypes_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Delegate Sub M(<InterpolatedStringHandlerArgument("""")> c As CustomHandler) <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @" M m = null; m($""""); "; var comp = CreateCompilation(code, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(4, 3) ); } [Fact] public void ArgumentsOnDelegateTypes_03() { var code = @" using System; using System.Runtime.CompilerServices; M m = (i, c) => Console.WriteLine(c.ToString()); m(1, $""""); delegate void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 5 .locals init (int V_0) IL_0000: ldsfld ""M Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""M..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""M Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: stloc.0 IL_0021: ldloc.0 IL_0022: ldc.i4.0 IL_0023: ldc.i4.0 IL_0024: ldloc.0 IL_0025: newobj ""CustomHandler..ctor(int, int, int)"" IL_002a: callvirt ""void M.Invoke(int, CustomHandler)"" IL_002f: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_01() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private int _i = 0; public CustomHandler(int literalLength, int formattedCount, int i = 1) => _i = i; public override string ToString() => _i.ToString(); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: ldc.i4.1 IL_0003: newobj ""CustomHandler..ctor(int, int, int)"" IL_0008: call ""void C.M(CustomHandler)"" IL_000d: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_02() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""Literal""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, out bool isValid, int i = 1) { _s = i.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (CustomHandler V_0, bool V_1) IL_0000: ldc.i4.7 IL_0001: ldc.i4.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.1 IL_0005: newobj ""CustomHandler..ctor(int, int, out bool, int)"" IL_000a: stloc.0 IL_000b: ldloc.1 IL_000c: brfalse.s IL_001a IL_000e: ldloca.s V_0 IL_0010: ldstr ""Literal"" IL_0015: call ""void CustomHandler.AppendLiteral(string)"" IL_001a: ldloc.0 IL_001b: call ""void C.M(CustomHandler)"" IL_0020: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_03() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, int i2 = 2) { _s = i1.ToString() + i2.ToString(); } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 5 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldc.i4.2 IL_0007: newobj ""CustomHandler..ctor(int, int, int, int)"" IL_000c: call ""void C.M(int, CustomHandler)"" IL_0011: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_04() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""Literal""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, out bool isValid, int i2 = 2) { _s = i1.ToString() + i2.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.7 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: ldc.i4.2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool, int)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_001e IL_0012: ldloca.s V_1 IL_0014: ldstr ""Literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: call ""void C.M(int, CustomHandler)"" IL_0024: ret } "); } [Fact] public void HandlerExtensionMethod_01() { var code = @" $""Test"".M(); public static class StringExt { public static void M(this CustomHandler handler) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (2,1): error CS1929: 'string' does not contain a definition for 'M' and the best extension method overload 'StringExt.M(CustomHandler)' requires a receiver of type 'CustomHandler' // $"Test".M(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$""Test""").WithArguments("string", "M", "StringExt.M(CustomHandler)", "CustomHandler").WithLocation(2, 1) ); } [Fact] public void HandlerExtensionMethod_02() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument("""")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // s.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(5, 5), // (14,38): error CS8944: 'S1Ext.M(S1, CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M(this S1 s, [InterpolatedStringHandlerArgument("")] CustomHandler c) => throw null; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("S1Ext.M(S1, CustomHandler)").WithLocation(14, 38) ); } [Fact] public void HandlerExtensionMethod_03() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1"); verifier.VerifyDiagnostics(); } [Fact] public void NoStandaloneConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,19): error CS7036: There is no argument given that corresponds to the required formal parameter 's' of 'CustomHandler.CustomHandler(int, int, string)' // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("s", "CustomHandler.CustomHandler(int, int, string)").WithLocation(4, 19), // (4,19): error CS1615: Argument 3 may not be passed with the 'out' keyword // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(4, 19) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class InterpolationTests : CompilingTestBase { [Fact] public void TestSimpleInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number }.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 }.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 }.""); Console.WriteLine($""Jenny don\'t change your number { number :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}.""); Console.WriteLine($""{number}""); } }"; string expectedOutput = @"Jenny don't change your number 8675309. Jenny don't change your number 8675309 . Jenny don't change your number 8675309. Jenny don't change your number 867-5309. Jenny don't change your number 867-5309 . Jenny don't change your number 867-5309. 8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestOnlyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}""); } }"; string expectedOutput = @"8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}{number}""); } }"; string expectedOutput = @"86753098675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}.""); } }"; string expectedOutput = @"Jenny don't change your number 867-5309 867-5309."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestEmptyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }.""); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,73): error CS1733: Expected expression // Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }."); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73) ); } [Fact] public void TestHalfOpenInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,63): error CS1010: Newline in constant // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63), // (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 // ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS8077: A single-line comment may not be used in an interpolated string. // Console.WriteLine($"Jenny don\'t change your number { 8675309 // "); Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp03() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 /* ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS1035: End-of-file found, '*/' expected // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71), // (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77), // (7,2): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2), // (7,2): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void LambdaInInterp() { string source = @"using System; class Program { static void Main(string[] args) { //Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() }); Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}""); } static int number = 8675309; } "; string expectedOutput = @"jenny (408) 867-5309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OneLiteral() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""Hello"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Hello"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } [Fact] public void OneInsert() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; Console.WriteLine( $""{hello}"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldstr ""Hello"" IL_0005: dup IL_0006: brtrue.s IL_000e IL_0008: pop IL_0009: ldstr """" IL_000e: call ""void System.Console.WriteLine(string)"" IL_0013: ret } "); } [Fact] public void TwoInserts() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $""{hello}, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TwoInserts02() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $@""{ hello }, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")] public void DynamicInterpolation() { string source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { dynamic nil = null; dynamic a = new string[] {""Hello"", ""world""}; Console.WriteLine($""<{nil}>""); Console.WriteLine($""<{a}>""); } Expression<Func<string>> M(dynamic d) { return () => $""Dynamic: {d}""; } }"; string expectedOutput = @"<> <System.String[]>"; var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnclosedInterpolation01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31), // (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35), // (7,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6), // (7,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6), // (8,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2)); } [Fact] public void UnclosedInterpolation02() { string source = @"class Program { static void Main(string[] args) { var x = $"";"; // The precise error messages are not important, but this must be an error. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,19): error CS1010: Newline in constant // var x = $"; Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19), // (5,20): error CS1002: ; expected // var x = $"; Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20) ); } [Fact] public void EmptyFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:}"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8089: Empty format specifier. // Console.WriteLine( $"{3:}" ); Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $"{3:d }" ); Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $@"{3:d Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d ").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS1733: Expected expression // Console.WriteLine( $"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32) ); } [Fact] public void MissingInterpolationExpression02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS1733: Expected expression // Console.WriteLine( $@"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression03() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( "; var normal = "$\""; var verbat = "$@\""; // ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail) Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline01() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" "" } ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline02() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" ""} ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void PreprocessorInsideInterpolation() { string source = @"class Program { static void Main() { var s = $@""{ #region : #endregion 0 }""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void EscapedCurly() { string source = @"class Program { static void Main() { var s1 = $"" \u007B ""; var s2 = $"" \u007D""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string. // var s1 = $" \u007B "; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21), // (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var s2 = $" \u007D"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21) ); } [Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")] public void NoFillIns01() { string source = @"class Program { static void Main() { System.Console.Write($""{{ x }}""); System.Console.WriteLine($@""This is a test""); } }"; string expectedOutput = @"{ x }This is a test"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BadAlignment() { string source = @"class Program { static void Main() { var s = $""{1,1E10}""; var t = $""{1,(int)1E10}""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22), // (5,22): error CS0150: A constant value is expected // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22), // (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override) // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22), // (6,22): error CS0150: A constant value is expected // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22) ); } [Fact] public void NestedInterpolatedVerbatim() { string source = @"using System; class Program { static void Main(string[] args) { var s = $@""{$@""{1}""}""; Console.WriteLine(s); } }"; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } // Since the platform type System.FormattableString is not yet in our platforms (at the // time of writing), we explicitly include the required platform types into the sources under test. private const string formattableString = @" /*============================================================ ** ** Class: FormattableString ** ** ** Purpose: implementation of the FormattableString ** class. ** ===========================================================*/ namespace System { /// <summary> /// A composite format string along with the arguments to be formatted. An instance of this /// type may result from the use of the C# or VB language primitive ""interpolated string"". /// </summary> public abstract class FormattableString : IFormattable { /// <summary> /// The composite format string. /// </summary> public abstract string Format { get; } /// <summary> /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> public abstract object[] GetArguments(); /// <summary> /// The number of arguments to be formatted. /// </summary> public abstract int ArgumentCount { get; } /// <summary> /// Returns one argument to be formatted from argument position <paramref name=""index""/>. /// </summary> public abstract object GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } /// <summary> /// Format the given object in the invariant culture. This static method may be /// imported in C# by /// <code> /// using static System.FormattableString; /// </code>. /// Within the scope /// of that import directive an interpolated string may be formatted in the /// invariant culture by writing, for example, /// <code> /// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"") /// </code> /// </summary> public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException(""formattable""); } return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); } } } /*============================================================ ** ** Class: FormattableStringFactory ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref=""FormattableString""/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format, params object[] arguments) { if (format == null) { throw new ArgumentNullException(""format""); } if (arguments == null) { throw new ArgumentNullException(""arguments""); } return new ConcreteFormattableString(format, arguments); } private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } public override object[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); } } } } "; [Fact] public void TargetType01() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; Console.Write(f is System.FormattableString); } }"; CompileAndVerify(source + formattableString, expectedOutput: "True"); } [Fact] public void TargetType02() { string source = @"using System; interface I1 { void M(String s); } interface I2 { void M(FormattableString s); } interface I3 { void M(IFormattable s); } interface I4 : I1, I2 {} interface I5 : I1, I3 {} interface I6 : I2, I3 {} interface I7 : I1, I2, I3 {} class C : I1, I2, I3, I4, I5, I6, I7 { public void M(String s) { Console.Write(1); } public void M(FormattableString s) { Console.Write(2); } public void M(IFormattable s) { Console.Write(3); } } class Program { public static void Main(string[] args) { C c = new C(); ((I1)c).M($""""); ((I2)c).M($""""); ((I3)c).M($""""); ((I4)c).M($""""); ((I5)c).M($""""); ((I6)c).M($""""); ((I7)c).M($""""); ((C)c).M($""""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "12311211"); } [Fact] public void MissingHelper() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; } }"; CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics( // (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported // IFormattable f = $"test"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26) ); } [Fact] public void AsyncInterp() { string source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { Task<string> hello = Task.FromResult(""Hello""); Task<string> world = Task.FromResult(""world""); M(hello, world).Wait(); } public static async Task M(Task<string> hello, Task<string> world) { Console.WriteLine($""{ await hello }, { await world }!""); } }"; CompileAndVerify( source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty); } [Fact] public void AlignmentExpression() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , -(3+4) }.""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "X = 123 ."); } [Fact] public void AlignmentMagnitude() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , (32768) }.""); Console.WriteLine($""X = { 123 , -(32768) }.""); Console.WriteLine($""X = { 123 , (32767) }.""); Console.WriteLine($""X = { 123 , -(32767) }.""); Console.WriteLine($""X = { 123 , int.MaxValue }.""); Console.WriteLine($""X = { 123 , int.MinValue }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , (32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42), // (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , -(32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41), // (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MaxValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41), // (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MinValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41) ); } [WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")] [Fact] public void InterpolationExpressionMustBeValue01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { String }.""); Console.WriteLine($""X = { null }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS0119: 'string' is a type, which is not valid in the given context // Console.WriteLine($"X = { String }."); Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35) ); } [Fact] public void InterpolationExpressionMustBeValue02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { x=>3 }.""); Console.WriteLine($""X = { Program.Main }.""); Console.WriteLine($""X = { Program.Main(null) }.""); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35), // (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS8917: The delegate type could not be inferred. // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x=>3").WithLocation(5, 35), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib01() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (15,21): error CS0117: 'string' does not contain a definition for 'Format' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib02() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Boolean Format(string format, int arg) { return true; } } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21) ); } [Fact] public void SillyCoreLib01() { var text = @"namespace System { interface IFormattable { } namespace Runtime.CompilerServices { public static class FormattableStringFactory { public static Bozo Create(string format, int arg) { return new Bozo(); } } } public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Bozo Format(string format, int arg) { return new Bozo(); } } public class FormattableString { } public class Bozo { public static implicit operator string(Bozo bozo) { return ""zz""; } public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); } } internal class Program { public static void Main() { var s1 = $""X = { 1 } ""; FormattableString s2 = $""X = { 1 } ""; } } }"; var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var compilation = CompileAndVerify(comp, verify: Verification.Fails); compilation.VerifyIL("System.Program.Main", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldstr ""X = {0} "" IL_0005: ldc.i4.1 IL_0006: call ""System.Bozo string.Format(string, int)"" IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)"" IL_0010: pop IL_0011: ldstr ""X = {0} "" IL_0016: ldc.i4.1 IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)"" IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)"" IL_0021: pop IL_0022: ret }"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax01() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):\}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40), // (6,40): error CS1009: Unrecognized escape sequence // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40) ); } [WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")] [Fact] public void Syntax02() { var text = @"using S = System; class C { void M() { var x = $""{ (S: } }"; // the precise diagnostics do not matter, as long as it is an error and not a crash. Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax03() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):}}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // var x = $"{ Math.Abs(value: 1):}}"; Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18) ); } [WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")] [Fact] public void NoUnexpandedForm() { string source = @"using System; class Program { public static void Main(string[] args) { string[] arr1 = new string[] { ""xyzzy"" }; object[] arr2 = arr1; Console.WriteLine($""-{null}-""); Console.WriteLine($""-{arr1}-""); Console.WriteLine($""-{arr2}-""); } }"; CompileAndVerify(source + formattableString, expectedOutput: @"-- -System.String[]- -System.String[]-"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Dynamic01() { var text = @"class C { const dynamic a = a; string s = $""{0,a}""; }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition // const dynamic a = a; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19), // (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null. // const dynamic a = a; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23), // (4,21): error CS0150: A constant value is expected // string s = $"{0,a}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21) ); } [WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")] [Fact] public void Syntax04() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<string>> e = () => $""\u1{0:\u2}""; Console.WriteLine(e); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,46): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46), // (8,52): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52) ); } [Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")] public void MissingConversionFromFormattableStringToIFormattable() { var text = @"namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) { return null; } } } namespace System { public abstract class FormattableString { } } static class C { static void Main() { System.IFormattable i = $""{""""}""; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics( // (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable' // System.IFormattable i = $"{""}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33) ); } [Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")] [InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")] [InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")] public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents) { var code = @" using System; Console.WriteLine(TwoComponents()); Console.WriteLine(ThreeComponents()); Console.WriteLine(FourComponents()); Console.WriteLine(FiveComponents()); string TwoComponents() { string s1 = ""1""; string s2 = ""2""; return " + twoComponents + @"; } string ThreeComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; return " + threeComponents + @"; } string FourComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; return " + fourComponents + @"; } string FiveComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; string s5 = ""5""; return " + fiveComponents + @"; } "; var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @" 12 123 1234 value:1 value:2 value:3 value:4 value:5 "); verifier.VerifyIL("Program.<<Main>$>g__TwoComponents|0_0()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (string V_0) //s2 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call ""string string.Concat(string, string)"" IL_0011: ret } "); verifier.VerifyIL("Program.<<Main>$>g__ThreeComponents|0_1()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (string V_0, //s2 string V_1) //s3 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldloc.0 IL_0012: ldloc.1 IL_0013: call ""string string.Concat(string, string, string)"" IL_0018: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FourComponents|0_2()", @" { // Code size 32 (0x20) .maxstack 4 .locals init (string V_0, //s2 string V_1, //s3 string V_2) //s4 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldstr ""4"" IL_0016: stloc.2 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""string string.Concat(string, string, string, string)"" IL_001f: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FiveComponents|0_3()", @" { // Code size 89 (0x59) .maxstack 3 .locals init (string V_0, //s1 string V_1, //s2 string V_2, //s3 string V_3, //s4 string V_4, //s5 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5) IL_0000: ldstr ""1"" IL_0005: stloc.0 IL_0006: ldstr ""2"" IL_000b: stloc.1 IL_000c: ldstr ""3"" IL_0011: stloc.2 IL_0012: ldstr ""4"" IL_0017: stloc.3 IL_0018: ldstr ""5"" IL_001d: stloc.s V_4 IL_001f: ldloca.s V_5 IL_0021: ldc.i4.0 IL_0022: ldc.i4.5 IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0030: ldloca.s V_5 IL_0032: ldloc.1 IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0038: ldloca.s V_5 IL_003a: ldloc.2 IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0040: ldloca.s V_5 IL_0042: ldloc.3 IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0048: ldloca.s V_5 IL_004a: ldloc.s V_4 IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0051: ldloca.s V_5 IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0058: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandler_OverloadsAndBoolReturns( bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @"int a = 1; System.Console.WriteLine(" + expression + @");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 80 (0x50) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldstr ""X"" IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.2 IL_0039: ldstr ""Y"" IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: ldloca.s V_1 IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0021: ldloca.s V_1 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 92 (0x5c) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_004d IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: brfalse.s IL_004d IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: brfalse.s IL_004d IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldstr ""X"" IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003b: brfalse.s IL_004d IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: br.s IL_004e IL_004d: ldc.i4.0 IL_004e: pop IL_004f: ldloca.s V_1 IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0056: call ""void System.Console.WriteLine(string)"" IL_005b: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_0051 IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0023: brfalse.s IL_0051 IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: brfalse.s IL_0051 IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldc.i4.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0047 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 88 (0x58) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004b IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: ldc.i4.0 IL_0033: ldstr ""X"" IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: ldloca.s V_1 IL_004d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0052: call ""void System.Console.WriteLine(string)"" IL_0057: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0051 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0051 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: brfalse.s IL_0051 IL_0027: ldloca.s V_1 IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0030: brfalse.s IL_0051 IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 100 (0x64) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0055 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0055 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0027: brfalse.s IL_0055 IL_0029: ldloca.s V_1 IL_002b: ldloc.0 IL_002c: ldc.i4.1 IL_002d: ldnull IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0033: brfalse.s IL_0055 IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.0 IL_0039: ldstr ""X"" IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: brfalse.s IL_0055 IL_0045: ldloca.s V_1 IL_0047: ldloc.0 IL_0048: ldc.i4.2 IL_0049: ldstr ""Y"" IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0053: br.s IL_0056 IL_0055: ldc.i4.0 IL_0056: pop IL_0057: ldloca.s V_1 IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005e: call ""void System.Console.WriteLine(string)"" IL_0063: ret } ", }; } [Fact] public void UseOfSpanInInterpolationHole_CSharp9() { var source = @" using System; ReadOnlySpan<char> span = stackalloc char[1]; Console.WriteLine($""{span}"");"; var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // Console.WriteLine($"{span}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22) ); } [ConditionalTheory(typeof(MonoOrCoreClrOnly))] [CombinatorialData] public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @" using System; ReadOnlySpan<char> a = ""1""; System.Console.WriteLine(" + expression + ");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldstr ""X"" IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: ldstr ""Y"" IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002a: ldloca.s V_1 IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0034: ldloca.s V_1 IL_0036: ldloc.0 IL_0037: ldc.i4.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 101 (0x65) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_0056 IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002a: brfalse.s IL_0056 IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: brfalse.s IL_0056 IL_0037: ldloca.s V_1 IL_0039: ldloc.0 IL_003a: ldstr ""X"" IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0044: brfalse.s IL_0056 IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: pop IL_0058: ldloca.s V_1 IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_005a IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002c: brfalse.s IL_005a IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: brfalse.s IL_005a IL_003a: ldloca.s V_1 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0050 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005a IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005a IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002e: brfalse.s IL_005a IL_0030: ldloca.s V_1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0039: brfalse.s IL_005a IL_003b: ldloca.s V_1 IL_003d: ldloc.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 97 (0x61) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0054 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: ldc.i4.0 IL_0028: ldnull IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: ldloca.s V_1 IL_003a: ldloc.0 IL_003b: ldc.i4.0 IL_003c: ldstr ""X"" IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: ldloca.s V_1 IL_0056: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005b: call ""void System.Console.WriteLine(string)"" IL_0060: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 109 (0x6d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005e IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005e IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0030: brfalse.s IL_005e IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldc.i4.1 IL_0036: ldnull IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_003c: brfalse.s IL_005e IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: ldstr ""X"" IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: brfalse.s IL_005e IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: ldc.i4.2 IL_0052: ldstr ""Y"" IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_005c: br.s IL_005f IL_005e: ldc.i4.0 IL_005f: pop IL_0060: ldloca.s V_1 IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0067: call ""void System.Console.WriteLine(string)"" IL_006c: ret } ", }; } [Theory] [InlineData(@"$""base{Throw()}{a = 2}""")] [InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")] public void BoolReturns_ShortCircuit(string expression) { var source = @" using System; int a = 1; Console.Write(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception();"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false"); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base 1"); } [Theory] [CombinatorialData] public void BoolOutParameter_ShortCircuits(bool useBoolReturns, [CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression) { var source = @" using System; int a = 1; Console.WriteLine(a); Console.WriteLine(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception(); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 1"); } [Theory] [InlineData(@"$""base{await Hole()}""")] [InlineData(@"$""base"" + $""{await Hole()}""")] public void AwaitInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @" { // Code size 164 (0xa4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00a3 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base{0}"" IL_0067: ldloc.1 IL_0068: box ""int"" IL_006d: call ""string string.Format(string, object)"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0090 } catch System.Exception { IL_0079: stloc.3 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0088: ldloc.3 IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008e: leave.s IL_00a3 } IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a3: ret } " : @" { // Code size 174 (0xae) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00ad IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base"" IL_0067: ldstr ""{0}"" IL_006c: ldloc.1 IL_006d: box ""int"" IL_0072: call ""string string.Format(string, object)"" IL_0077: call ""string string.Concat(string, string)"" IL_007c: call ""void System.Console.WriteLine(string)"" IL_0081: leave.s IL_009a } catch System.Exception { IL_0083: stloc.3 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0092: ldloc.3 IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0098: leave.s IL_00ad } IL_009a: ldarg.0 IL_009b: ldc.i4.s -2 IL_009d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00a2: ldarg.0 IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00ad: ret }"); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = await Hole(); Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base value:1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 185 (0xb9) .maxstack 3 .locals init (int V_0, int V_1, //hole System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00b8 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldc.i4.4 IL_0063: ldc.i4.1 IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0069: stloc.3 IL_006a: ldloca.s V_3 IL_006c: ldstr ""base"" IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0076: ldloca.s V_3 IL_0078: ldloc.1 IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_007e: ldloca.s V_3 IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0085: call ""void System.Console.WriteLine(string)"" IL_008a: leave.s IL_00a5 } catch System.Exception { IL_008c: stloc.s V_4 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009c: ldloc.s V_4 IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a3: leave.s IL_00b8 } IL_00a5: ldarg.0 IL_00a6: ldc.i4.s -2 IL_00a8: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00ad: ldarg.0 IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b8: ret } "); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = 2; Test(await M(1), " + expression + @", await M(3)); void Test(int i1, string s, int i2) => Console.WriteLine(s); Task<int> M(int i) { Console.WriteLine(i); return Task.FromResult(1); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 3 base value:2"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 328 (0x148) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0050 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00dc IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: stfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0018: ldc.i4.1 IL_0019: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0023: stloc.2 IL_0024: ldloca.s V_2 IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002b: brtrue.s IL_006c IL_002d: ldarg.0 IL_002e: ldc.i4.0 IL_002f: dup IL_0030: stloc.0 IL_0031: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0036: ldarg.0 IL_0037: ldloc.2 IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003d: ldarg.0 IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0043: ldloca.s V_2 IL_0045: ldarg.0 IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004b: leave IL_0147 IL_0050: ldarg.0 IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0056: stloc.2 IL_0057: ldarg.0 IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0063: ldarg.0 IL_0064: ldc.i4.m1 IL_0065: dup IL_0066: stloc.0 IL_0067: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006c: ldarg.0 IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0079: ldarg.0 IL_007a: ldc.i4.4 IL_007b: ldc.i4.1 IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0081: stloc.3 IL_0082: ldloca.s V_3 IL_0084: ldstr ""base"" IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_008e: ldloca.s V_3 IL_0090: ldarg.0 IL_0091: ldfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_009b: ldloca.s V_3 IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00a2: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_00a7: ldc.i4.3 IL_00a8: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00b2: stloc.2 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00ba: brtrue.s IL_00f8 IL_00bc: ldarg.0 IL_00bd: ldc.i4.1 IL_00be: dup IL_00bf: stloc.0 IL_00c0: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldloc.2 IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00cc: ldarg.0 IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d2: ldloca.s V_2 IL_00d4: ldarg.0 IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_00da: leave.s IL_0147 IL_00dc: ldarg.0 IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e2: stloc.2 IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00ef: ldarg.0 IL_00f0: ldc.i4.m1 IL_00f1: dup IL_00f2: stloc.0 IL_00f3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00f8: ldloca.s V_2 IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ff: stloc.1 IL_0100: ldarg.0 IL_0101: ldfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0106: ldarg.0 IL_0107: ldfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_010c: ldloc.1 IL_010d: call ""void Program.<<Main>$>g__Test|0_0(int, string, int)"" IL_0112: ldarg.0 IL_0113: ldnull IL_0114: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_0119: leave.s IL_0134 } catch System.Exception { IL_011b: stloc.s V_4 IL_011d: ldarg.0 IL_011e: ldc.i4.s -2 IL_0120: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0125: ldarg.0 IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_012b: ldloc.s V_4 IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0132: leave.s IL_0147 } IL_0134: ldarg.0 IL_0135: ldc.i4.s -2 IL_0137: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0147: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void DynamicInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 3 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base"" IL_000c: ldstr ""{0}"" IL_0011: ldloc.0 IL_0012: call ""string string.Format(string, object)"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{hole}base""")] [InlineData(@"$""{hole}"" + $""base""")] public void DynamicInHoles_UsesFormat2(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"1base"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: ldstr ""base"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}base"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Fact] public void ImplicitConversionsInConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(object literalLength, object formattedCount) {} } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerAttribute }); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: box ""int"" IL_000c: newobj ""CustomHandler..ctor(object, object)"" IL_0011: pop IL_0012: ret } "); } [Fact] public void MissingCreate_01() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_02() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_03() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5) ); } [Theory] [InlineData(null)] [InlineData("public string ToStringAndClear(int literalLength) => throw null;")] [InlineData("public void ToStringAndClear() => throw null;")] [InlineData("public static string ToStringAndClear() => throw null;")] public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod) { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; " + toStringAndClearMethod + @" public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5) ); } [Fact] public void ObsoleteCreateMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { [System.Obsolete(""Constructor is obsolete"", error: true)] public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5) ); } [Fact] public void ObsoleteAppendLiteralMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; [System.Obsolete(""AppendLiteral is obsolete"", error: true)] public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7) ); } [Fact] public void ObsoleteAppendFormattedMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; [System.Obsolete(""AppendFormatted is obsolete"", error: true)] public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11) ); } private const string UnmanagedCallersOnlyIl = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } }"; [Fact] public void UnmanagedCallersOnlyAppendFormattedMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance void Dispose () cil managed { ldnull throw } .method public hidebysig virtual instance string ToString () cil managed { ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics( // (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7) ); } [Fact] public void UnmanagedCallersOnlyToStringMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance string ToStringAndClear () cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5) ); } [Theory] [InlineData(@"$""{i}{s}""")] [InlineData(@"$""{i}"" + $""{s}""")] public void UnsupportedArgumentType(string expression) { var source = @" unsafe { int* i = null; var s = new S(); _ = " + expression + @"; } ref struct S { }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (6,11): error CS0306: The type 'int*' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11), // (6,14): error CS0306: The type 'S' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length) ); } [Theory] [InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")] [InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")] public void TargetTypedInterpolationHoles(string expression) { var source = @" bool b = true; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2 value: value:"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 81 (0x51) .maxstack 3 .locals init (bool V_0, //b object V_1, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.0 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloc.0 IL_000c: brfalse.s IL_0017 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: stloc.1 IL_0015: br.s IL_0019 IL_0017: ldnull IL_0018: stloc.1 IL_0019: ldloca.s V_2 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0021: ldloca.s V_2 IL_0023: ldloc.0 IL_0024: brfalse.s IL_002e IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: br.s IL_002f IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0034: ldloca.s V_2 IL_0036: ldnull IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_003c: ldloca.s V_2 IL_003e: ldnull IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0044: ldloca.s V_2 IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Theory] [InlineData(@"$""{(null, default)}{new()}""")] [InlineData(@"$""{(null, default)}"" + $""{new()}""")] public void TargetTypedInterpolationHoles_Errors(string expression) { var source = @"System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object' // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29), // (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29), // (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length) ); } [Fact] public void RefTernary() { var source = @" bool b = true; int i = 1; System.Console.WriteLine($""{(!b ? ref i : ref i)}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); } [Fact] public void NestedInterpolatedStrings_01() { var source = @" int i = 1; System.Console.WriteLine($""{$""{i}""}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0013: ldloca.s V_1 IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret } "); } [Theory] [InlineData(@"$""{$""{i1}""}{$""{i2}""}""")] [InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")] public void NestedInterpolatedStrings_02(string expression) { var source = @" int i1 = 1; int i2 = 2; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 63 (0x3f) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldloca.s V_2 IL_0006: ldc.i4.0 IL_0007: ldc.i4.1 IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0015: ldloca.s V_2 IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001c: ldloca.s V_2 IL_001e: ldc.i4.0 IL_001f: ldc.i4.1 IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0025: ldloca.s V_2 IL_0027: ldloc.1 IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_002d: ldloca.s V_2 IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0034: call ""string string.Concat(string, string)"" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: ret } "); } [Fact] public void ExceptionFilter_01() { var source = @" using System; int i = 1; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = i }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{i}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public int Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 .try { IL_0002: ldstr ""Starting try"" IL_0007: call ""void System.Console.WriteLine(string)"" IL_000c: newobj ""MyException..ctor()"" IL_0011: dup IL_0012: ldloc.0 IL_0013: callvirt ""void MyException.Prop.set"" IL_0018: throw } filter { IL_0019: isinst ""MyException"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldc.i4.0 IL_0023: br.s IL_004f IL_0025: callvirt ""string object.ToString()"" IL_002a: ldloca.s V_1 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0033: ldloca.s V_1 IL_0035: ldloc.0 IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_003b: ldloca.s V_1 IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0042: callvirt ""string string.Trim()"" IL_0047: call ""bool string.op_Equality(string, string)"" IL_004c: ldc.i4.0 IL_004d: cgt.un IL_004f: endfilter } // end filter { // handler IL_0051: pop IL_0052: ldstr ""Caught"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: leave.s IL_005e } IL_005e: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ExceptionFilter_02() { var source = @" using System; ReadOnlySpan<char> s = new char[] { 'i' }; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = s.ToString() }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{s}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public string Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: newarr ""char"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 105 IL_000a: stelem.i2 IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])"" IL_0010: stloc.0 .try { IL_0011: ldstr ""Starting try"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: newobj ""MyException..ctor()"" IL_0020: dup IL_0021: ldloca.s V_0 IL_0023: constrained. ""System.ReadOnlySpan<char>"" IL_0029: callvirt ""string object.ToString()"" IL_002e: callvirt ""void MyException.Prop.set"" IL_0033: throw } filter { IL_0034: isinst ""MyException"" IL_0039: dup IL_003a: brtrue.s IL_0040 IL_003c: pop IL_003d: ldc.i4.0 IL_003e: br.s IL_006a IL_0040: callvirt ""string object.ToString()"" IL_0045: ldloca.s V_1 IL_0047: ldc.i4.0 IL_0048: ldc.i4.1 IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0056: ldloca.s V_1 IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005d: callvirt ""string string.Trim()"" IL_0062: call ""bool string.op_Equality(string, string)"" IL_0067: ldc.i4.0 IL_0068: cgt.un IL_006a: endfilter } // end filter { // handler IL_006c: pop IL_006d: ldstr ""Caught"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0079 } IL_0079: ret } "); } [ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] [InlineData(@"$""{s}{c}""")] [InlineData(@"$""{s}"" + $""{c}""")] public void ImplicitUserDefinedConversionInHole(string expression) { var source = @" using System; S s = default; C c = new C(); Console.WriteLine(" + expression + @"); ref struct S { public static implicit operator ReadOnlySpan<char>(S s) => ""S converted""; } class C { public static implicit operator ReadOnlySpan<char>(C s) => ""C converted""; }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:S converted value:C"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, //s C V_1, //c System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: newobj ""C..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.0 IL_0011: ldc.i4.2 IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0024: ldloca.s V_2 IL_0026: ldloc.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)"" IL_002c: ldloca.s V_2 IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ExplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; Console.WriteLine($""{s}""); ref struct S { public static explicit operator ReadOnlySpan<char>(S s) => ""S converted""; } "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,21): error CS0306: The type 'S' may not be used as a type argument // Console.WriteLine($"{s}"); Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ImplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static implicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var verifier = CompileAndVerify(source, expectedOutput: @" literal:Text value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 52 (0x34) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Text"" IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)"" IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.1 IL_001d: box ""int"" IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0027: ldloca.s V_0 IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } "); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ExplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static explicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct' // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void InvalidBuilderReturnType(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public int AppendLiteral(string s) => 0; public int AppendFormatted(object o) => 0; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21), // (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length) ); } [Fact] public void MissingAppendMethods() { var source = @" using System.Runtime.CompilerServices; CustomHandler c = $""Literal{1}""; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } } "; var comp = CreateCompilation(new[] { source, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,21): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 21), // (4,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Literal").WithArguments("?.()").WithLocation(4, 21), // (4,28): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{1}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 28), // (4,28): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("?.()").WithLocation(4, 28) ); } [Fact] public void MissingBoolType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @"CustomHandler c = $""Literal{1}"";"; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyDiagnostics( // (1,19): error CS0518: Predefined type 'System.Boolean' is not defined or imported // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""Literal{1}""").WithArguments("System.Boolean").WithLocation(1, 19) ); } [Fact] public void MissingVoidType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @" class C { public bool M() { CustomHandler c = $""Literal{1}""; return true; } } "; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Void); comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_01(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length) ); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_02(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(string s) { } public bool AppendFormatted(object o) => true; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length) ); } [Fact] public void MixedBuilderReturnTypes_03() { var source = @" using System; Console.WriteLine($""{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { _builder.AppendLine(""value:"" + o.ToString()); } } }"; CompileAndVerify(source, expectedOutput: "value:1"); } [Fact] public void MixedBuilderReturnTypes_04() { var source = @" using System; using System.Text; using System.Runtime.CompilerServices; Console.WriteLine((CustomHandler)$""l""); [InterpolatedStringHandler] public class CustomHandler { private readonly StringBuilder _builder; public CustomHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public override string ToString() => _builder.ToString(); public bool AppendFormatted(object o) => true; public void AppendLiteral(string s) { _builder.AppendLine(""literal:"" + s.ToString()); } } "; CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l"); } private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler") { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var descendentNodes = tree.GetRoot().DescendantNodes(); var interpolatedString = (ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>() .Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any()) .FirstOrDefault() ?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(interpolatedString); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.Exists); Assert.True(semanticInfo.ImplicitConversion.IsValid); Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler); Assert.Null(semanticInfo.ImplicitConversion.Method); if (interpolatedString is BinaryExpressionSyntax) { Assert.False(semanticInfo.ConstantValue.HasValue); AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString()); } // https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings. } private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput) => CompileAndVerify( compilation, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); [Theory] [CombinatorialData] public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns, [CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression) { var code = @" CustomHandler builder = " + expression + @"; System.Console.WriteLine(builder.ToString());"; var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns); var comp = CreateCompilation(new[] { code, builder }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:Literal value:1 alignment:2 format:f"); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (type, useBoolReturns) switch { (type: "struct", useBoolReturns: true) => @" { // Code size 67 (0x43) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""bool CustomHandler.AppendLiteral(string)"" IL_0015: brfalse.s IL_002c IL_0017: ldloca.s V_1 IL_0019: ldc.i4.1 IL_001a: box ""int"" IL_001f: ldc.i4.2 IL_0020: ldstr ""f"" IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: constrained. ""CustomHandler"" IL_0038: callvirt ""string object.ToString()"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } ", (type: "struct", useBoolReturns: false) => @" { // Code size 61 (0x3d) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(string)"" IL_0015: ldloca.s V_1 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldc.i4.2 IL_001e: ldstr ""f"" IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0028: ldloc.1 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""CustomHandler"" IL_0032: callvirt ""string object.ToString()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } ", (type: "class", useBoolReturns: true) => @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""Literal"" IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0013: brfalse.s IL_0029 IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: box ""int"" IL_001c: ldc.i4.2 IL_001d: ldstr ""f"" IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret } ", (type: "class", useBoolReturns: false) => @" { // Code size 47 (0x2f) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldstr ""Literal"" IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: box ""int"" IL_0019: ldc.i4.2 IL_001a: ldstr ""f"" IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret } ", _ => throw ExceptionUtilities.Unreachable }; } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void CustomHandlerMethodArgument(string expression) { var code = @" M(" + expression + @"); void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"($""{1,2:f}"" + $""Literal"")")] public void ExplicitHandlerCast_InCode(string expression) { var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); syntax = ((CastExpressionSyntax)syntax).Expression; Assert.Equal(expression, syntax.ToString()); semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); // https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: call ""void System.Console.WriteLine(object)"" IL_0029: ret } "); } [Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void HandlerConversionPreferredOverStringForNonConstant(string expression) { var code = @" CultureInfoNormalizer.Normalize(); C.M(" + expression + @"); class C { public static void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.7 IL_0006: ldc.i4.1 IL_0007: newobj ""CustomHandler..ctor(int, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldc.i4.2 IL_0015: ldstr ""f"" IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001f: brfalse.s IL_002e IL_0021: ldloc.0 IL_0022: ldstr ""Literal"" IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: pop IL_0030: ldloc.0 IL_0031: call ""void C.M(CustomHandler)"" IL_0036: ret } "); comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9); verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: ldstr ""Literal"" IL_001a: call ""string string.Concat(string, string)"" IL_001f: call ""void C.M(string)"" IL_0024: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}Literal"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: call ""void C.M(string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler b) { throw null; } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Literal"" IL_0005: call ""void C.M(string)"" IL_000a: ret } "); } [Theory] [InlineData(@"$""{1}{2}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type // [Attr($"{1}{2}")] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2) ); VerifyInterpolatedStringExpression(comp); var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); void validate(ModuleSymbol m) { var attr = m.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => throw null; public static void M(CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); comp.VerifyDiagnostics( // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)' // C.M($""); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_01(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_02(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_03(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'. // C.M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_01(string expression) { var code = @" C.M(" + expression + @", default(CustomHandler)); C.M(default(CustomHandler), " + expression + @"); class C { public static void M<T>(T t1, T t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M($"{1,2:f}Literal", default(CustomHandler)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3), // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_02(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), () => $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_03(string expression) { var code = @" using System; C.M(" + expression + @", default(CustomHandler)); class C { public static void M<T>(T t1, T t2) => Console.WriteLine(t1); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 51 (0x33) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ldnull IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)"" IL_0032: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_04(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2()); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_01(string expression) { var code = @" using System; Func<CustomHandler> f = () => " + expression + @"; Console.WriteLine(f()); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_02(string expression) { var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(() => " + expression + @"); class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } "; // Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string, // so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec). var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); // No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldstr ""{0,2:f}Literal"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldstr ""{0,2:f}"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ldstr ""Literal"" IL_0015: call ""string string.Concat(string, string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_03(string expression) { // Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct // when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to // fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>. var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => throw null; public static void M(Func<CustomHandler> f) => Console.WriteLine(f()); } public partial class CustomHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } public ref struct S { public string Field { get; set; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 35 (0x23) .maxstack 4 .locals init (S V_0) IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldloca.s V_0 IL_000a: initobj ""S"" IL_0010: ldloca.s V_0 IL_0012: ldstr ""Field"" IL_0017: call ""void S.Field.set"" IL_001c: ldloc.0 IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)"" IL_0022: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_04(string expression) { // Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type) var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } public partial class CustomHandler { public void AppendFormatted(S value) => throw null; } public ref struct S { public string Field { get; set; } } namespace System.Runtime.CompilerServices { public ref partial struct DefaultInterpolatedStringHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } } "; string[] source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false), GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11), // (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloca.s V_1 IL_000d: initobj ""S"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""Field"" IL_001a: call ""void S.Field.set"" IL_001f: ldloc.1 IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)"" IL_0025: ldloca.s V_0 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_05(string expression) { var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => throw null; public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_06(string expression) { // Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion // means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec) // and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type // has an identity conversion to the return type of Func<bool, string>, that is preferred. var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @" { // Code size 35 (0x23) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ret } " : @" { // Code size 45 (0x2d) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_07(string expression) { // Same as 5, but with an implicit conversion from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } public partial struct CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_08(string expression) { // Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)' // C.M(b => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void LambdaInference_AmbiguousInOlderLangVersions(string expression) { var code = @" using System; C.M(param => { param = " + expression + @"; }); static class C { public static void M(Action<string> f) => throw null; public static void M(Action<CustomHandler> f) => throw null; } "; var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); // This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04 // We should not be changing binding behavior based on LangVersion. comp.VerifyEmitDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)' // C.M(param => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_01(string expression) { var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06 var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 56 (0x38) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_0024 IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: br.s IL_0032 IL_0024: ldloca.s V_0 IL_0026: initobj ""CustomHandler"" IL_002c: ldloc.0 IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } " : @" { // Code size 66 (0x42) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_002e IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: br.s IL_003c IL_002e: ldloca.s V_0 IL_0030: initobj ""CustomHandler"" IL_0036: ldloc.0 IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_03(string expression) { // Same as 02, but with a target-type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_04(string expression) { // Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07 var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_05(string expression) { // Same 01, but with a conversion from string to CustomHandler and CustomHandler to string. var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another // var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_06(string expression) { // Same 05, but with a target type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0046: call ""void System.Console.WriteLine(string)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_01(string expression) { // Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types // and not on expression conversions, no best type can be found for this switch expression. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string. var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 59 (0x3b) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_0034 IL_0023: ldstr ""{0,2:f}Literal"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } " : @" { // Code size 69 (0x45) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_003e IL_0023: ldstr ""{0,2:f}"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: ldstr ""Literal"" IL_0038: call ""string string.Concat(string, string)"" IL_003d: stloc.0 IL_003e: ldloc.0 IL_003f: call ""void System.Console.WriteLine(string)"" IL_0044: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_03(string expression) { // Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile). var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_04(string expression) { // Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: box ""CustomHandler"" IL_0049: call ""void System.Console.WriteLine(object)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_05(string expression) { // Same as 01, but with conversions in both directions. No best common type can be found. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_06(string expression) { // Same as 05, but with a target type. var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_01(string expression) { var code = @" M(" + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(ref CustomHandler)"" IL_002f: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_02(string expression) { var code = @" M(" + expression + @"); M(ref " + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword // M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3), // (3,7): error CS1510: A ref or out value must be an assignable variable // M(ref $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_03(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 5 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_04(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002f: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void RefOverloadResolution_MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => System.Console.WriteLine(c); public static void M(ref CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); VerifyInterpolatedStringExpression(comp, "CustomHandler1"); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler1 V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler1..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler1.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler1)"" IL_002e: ret } "); } private const string InterpolatedStringHandlerAttributesVB = @" Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerAttribute Inherits Attribute End Class <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute Inherits Attribute Public Sub New(argument As String) Arguments = { argument } End Sub Public Sub New(ParamArray arguments() as String) Me.Arguments = arguments End Sub Public ReadOnly Property Arguments As String() End Class End Namespace "; [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (8,27): error CS8946: 'string' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27) ); var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String) End Sub End Class "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); // Note: there is no compilation error here because the natural type of a string is still string, and // we just bind to that method without checking the handler attribute. var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string' // public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70) ); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'. // public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34), // (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; _ = new C(" + expression + @"); class C { public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11), // (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression) { var code = @" using System.Runtime.CompilerServices; C<CustomHandler>.M(" + expression + @"); public class C<T> { public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20), // (8,27): error CS8946: 'T' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27) ); var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C"); var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler"); var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler))); var cParam = substitutedC.GetMethod("M").Parameters.Single(); Assert.IsType<SubstitutedParameterSymbol>(cParam); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C(Of T) Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var goodCode = @" int i = 10; C.M(i: i, c: " + expression + @"); "; var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @" i:10 literal:text "); verifier.VerifyDiagnostics( // (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller // to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); verifyIL(verifier); var badCode = @"C.M(" + expression + @", 1);"; comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'. // C.M($"", 1); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length), // (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller // to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } void verifyIL(CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 36 (0x24) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldloca.s V_2 IL_0007: ldc.i4.4 IL_0008: ldc.i4.0 IL_0009: ldloc.0 IL_000a: call ""CustomHandler..ctor(int, int, int)"" IL_000f: ldloca.s V_2 IL_0011: ldstr ""text"" IL_0016: call ""bool CustomHandler.AppendLiteral(string)"" IL_001b: pop IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call ""void C.M(CustomHandler, int)"" IL_0023: ret } " : @" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldc.i4.4 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_3 IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000f: stloc.2 IL_0010: ldloc.3 IL_0011: brfalse.s IL_0021 IL_0013: ldloca.s V_2 IL_0015: ldstr ""text"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.2 IL_0024: ldloc.1 IL_0025: call ""void C.M(CustomHandler, int)"" IL_002a: ret } "); } } [Fact] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { private CustomHandler(int literalLength, int formattedCount, int i) : this() {} static void InCustomHandler() { C.M(1, " + expression + @"); } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() }); comp.VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8) ); comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics) { var code = @" using System.Runtime.CompilerServices; int i = 0; C.M(" + mRef + @" i, " + expression + @"); public class C { public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression, // (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6)); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this() { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var expectedDiagnostics = extraConstructorArg == "" ? new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5) } : new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)' // C.M(1, $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8) }; var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { comp = CreateCompilation(executableCode, new[] { d }); comp.VerifyDiagnostics(expectedDiagnostics); } static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString(); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" using System; int i = 10; Console.WriteLine(C.M(i, " + expression + @")); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 39 (0x27) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.1 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""CustomHandler..ctor(int, int, int)"" IL_000e: ldloca.s V_1 IL_0010: ldstr ""2"" IL_0015: call ""bool CustomHandler.AppendLiteral(string)"" IL_001a: pop IL_001b: ldloc.1 IL_001c: call ""string C.M(int, CustomHandler)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } " : @" { // Code size 46 (0x2e) .maxstack 5 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: ldloc.0 IL_0007: ldloca.s V_2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0020 IL_0012: ldloca.s V_1 IL_0014: ldstr ""2"" IL_0019: call ""bool CustomHandler.AppendLiteral(string)"" IL_001e: br.s IL_0021 IL_0020: ldc.i4.0 IL_0021: pop IL_0022: ldloc.1 IL_0023: call ""string C.M(int, CustomHandler)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" int i = 10; string s = ""arg""; C.M(i, s, " + expression + @"); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); string expectedOutput = @" i:10 s:arg literal:literal "; var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol verifier) { var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 44 (0x2c) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldloca.s V_3 IL_000f: ldc.i4.7 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloc.2 IL_0013: call ""CustomHandler..ctor(int, int, int, string)"" IL_0018: ldloca.s V_3 IL_001a: ldstr ""literal"" IL_001f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0024: pop IL_0025: ldloc.3 IL_0026: call ""void C.M(int, string, CustomHandler)"" IL_002b: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldc.i4.7 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: ldloc.2 IL_0011: ldloca.s V_4 IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_0018: stloc.3 IL_0019: ldloc.s V_4 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_3 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.3 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; string s = null; object o; C.M(i, ref s, out o, " + expression + @"); Console.WriteLine(s); Console.WriteLine(o); public class C { public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c) { Console.WriteLine(s); o = ""o in M""; s = ""s in M""; Console.Write(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount) { o = null; s = ""s in constructor""; _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" s in constructor i:1 literal:literal s in M o in M "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 67 (0x43) .maxstack 8 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)"" IL_0020: stloc.s V_6 IL_0022: ldloca.s V_6 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: pop IL_002f: ldloc.s V_6 IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_0036: ldloc.1 IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldloc.2 IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: ret } " : @" { // Code size 76 (0x4c) .maxstack 9 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6, bool V_7) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: ldloca.s V_7 IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)"" IL_0022: stloc.s V_6 IL_0024: ldloc.s V_7 IL_0026: brfalse.s IL_0036 IL_0028: ldloca.s V_6 IL_002a: ldstr ""literal"" IL_002f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0034: br.s IL_0037 IL_0036: ldc.i4.0 IL_0037: pop IL_0038: ldloc.s V_6 IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_003f: ldloc.1 IL_0040: call ""void System.Console.WriteLine(string)"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), GetString(), " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt GetString s:str i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 45 (0x2d) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: call ""CustomHandler..ctor(int, int, string, int)"" IL_0019: ldloca.s V_2 IL_001b: ldstr ""literal"" IL_0020: call ""bool CustomHandler.AppendLiteral(string)"" IL_0025: pop IL_0026: ldloc.2 IL_0027: call ""void C.M(int, string, CustomHandler)"" IL_002c: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_3 IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)"" IL_0019: stloc.2 IL_001a: ldloc.3 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_2 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.2 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetC().M(s: GetString(), i: GetInt(), c: " + expression + @"); C GetC() { Console.WriteLine(""GetC""); return new C { Field = 5 }; } int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public int Field; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""c.Field:"" + c.Field.ToString()); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetC GetString GetInt s:str c.Field:5 i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 56 (0x38) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldloca.s V_4 IL_0019: ldc.i4.7 IL_001a: ldc.i4.0 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldloc.2 IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)"" IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""bool CustomHandler.AppendLiteral(string)"" IL_002f: pop IL_0030: ldloc.s V_4 IL_0032: callvirt ""void C.M(int, string, CustomHandler)"" IL_0037: ret } " : @" { // Code size 65 (0x41) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4, bool V_5) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldc.i4.7 IL_0018: ldc.i4.0 IL_0019: ldloc.0 IL_001a: ldloc.1 IL_001b: ldloc.2 IL_001c: ldloca.s V_5 IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)"" IL_0023: stloc.s V_4 IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0037 IL_0029: ldloca.s V_4 IL_002b: ldstr ""literal"" IL_0030: call ""bool CustomHandler.AppendLiteral(string)"" IL_0035: br.s IL_0038 IL_0037: ldc.i4.0 IL_0038: pop IL_0039: ldloc.s V_4 IL_003b: callvirt ""void C.M(int, string, CustomHandler)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), """", " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""i2:"" + i2.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt i1:10 i2:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 43 (0x2b) .maxstack 7 .locals init (int V_0, CustomHandler V_1) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: call ""CustomHandler..ctor(int, int, int, int)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: call ""void C.M(int, string, CustomHandler)"" IL_002a: ret } " : @" { // Code size 50 (0x32) .maxstack 7 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldc.i4.7 IL_000d: ldc.i4.0 IL_000e: ldloc.0 IL_000f: ldloc.0 IL_0010: ldloca.s V_2 IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: brfalse.s IL_0029 IL_001b: ldloca.s V_1 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.1 IL_002c: call ""void C.M(int, string, CustomHandler)"" IL_0031: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, """", " + expression + @"); public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: newobj ""CustomHandler..ctor(int, int)"" IL_000d: call ""void C.M(int, string, CustomHandler)"" IL_0012: ret } " : @" { // Code size 21 (0x15) .maxstack 5 .locals init (bool V_0) IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)"" IL_000f: call ""void C.M(int, string, CustomHandler)"" IL_0014: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { } } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics( (extraConstructorArg == "") ? new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12), // (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12) } : new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12), // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12) } ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); Console.WriteLine(c[10, ""str"", " + expression + @"]); public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: callvirt ""string C.this[int, string, CustomHandler].get"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""string C.this[int, string, CustomHandler].get"" IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); c[10, ""str"", " + expression + @"] = """"; public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: ldstr """" IL_002e: callvirt ""void C.this[int, string, CustomHandler].set"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: ldstr """" IL_0035: callvirt ""void C.this[int, string, CustomHandler].set"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; (new C(5)).M((int)10, ""str"", " + expression + @"); public class C { public int Prop { get; } public C(int i) => Prop = i; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""c.Prop:"" + c.Prop.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 c.Prop:5 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 51 (0x33) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_3 IL_0015: ldc.i4.7 IL_0016: ldc.i4.0 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)"" IL_001f: ldloca.s V_3 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: pop IL_002c: ldloc.3 IL_002d: callvirt ""void C.M(int, string, CustomHandler)"" IL_0032: ret } " : @" { // Code size 59 (0x3b) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: ldloc.1 IL_0017: ldloc.2 IL_0018: ldloca.s V_4 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)"" IL_001f: stloc.3 IL_0020: ldloc.s V_4 IL_0022: brfalse.s IL_0032 IL_0024: ldloca.s V_3 IL_0026: ldstr ""literal"" IL_002b: call ""bool CustomHandler.AppendLiteral(string)"" IL_0030: br.s IL_0033 IL_0032: ldc.i4.0 IL_0033: pop IL_0034: ldloc.3 IL_0035: callvirt ""void C.M(int, string, CustomHandler)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(5, " + expression + @"); public class C { public int Prop { get; } public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" i:5 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 34 (0x22) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldloca.s V_1 IL_0005: ldc.i4.7 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: call ""CustomHandler..ctor(int, int, int)"" IL_000d: ldloca.s V_1 IL_000f: ldstr ""literal"" IL_0014: call ""bool CustomHandler.AppendLiteral(string)"" IL_0019: pop IL_001a: ldloc.1 IL_001b: newobj ""C..ctor(int, CustomHandler)"" IL_0020: pop IL_0021: ret } "); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_Success([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: callvirt ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_Success_StructReceiver([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public struct C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: call ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: call ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC().M(" + expression + @"); " + refness + @" C GetC() => throw null; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC().M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10) ); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); ref C GetC(ref C c) => ref c; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "ref").WithLocation(5, 15) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Rvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(s2, " + expression + @"); public struct S { public int I; public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" s1.I:1 s2.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 6 .locals init (S V_0, //s2 S V_1, S V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: ldloca.s V_1 IL_0013: initobj ""S"" IL_0019: ldloca.s V_1 IL_001b: ldc.i4.2 IL_001c: stfld ""int S.I"" IL_0021: ldloc.1 IL_0022: stloc.0 IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldloc.1 IL_002c: ldloc.2 IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)"" IL_0032: call ""void S.M(S, CustomHandler)"" IL_0037: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Lvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(ref s2, " + expression + @"); public struct S { public int I; public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword // s1.M(ref s2, $""); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByVal(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(s, " + expression + @"); public struct S { public int I; public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.0 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: newobj ""CustomHandler..ctor(int, int, S)"" IL_001b: call ""void S.M(S, CustomHandler)"" IL_0020: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByRef(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(ref s, " + expression + @"); public struct S { public int I; public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 36 (0x24) .maxstack 4 .locals init (S V_0, //s S V_1, S& V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldc.i4.0 IL_0017: ldc.i4.0 IL_0018: ldloc.2 IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)"" IL_001e: call ""void S.M(ref S, CustomHandler)"" IL_0023: ret } "); } [Theory] [CombinatorialData] public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetReceiver().M( GetArg(""Unrelated parameter 1""), GetArg(""Second value""), GetArg(""Unrelated parameter 2""), GetArg(""First value""), " + expression + @", GetArg(""Unrelated parameter 4"")); C GetReceiver() { Console.WriteLine(""GetReceiver""); return new C() { Prop = ""Prop"" }; } string GetArg(string s) { Console.WriteLine(s); return s; } public class C { public string Prop { get; set; } public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""s1:"" + s1); _builder.AppendLine(""c.Prop:"" + c.Prop); _builder.AppendLine(""s2:"" + s2); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @" GetReceiver Unrelated parameter 1 Second value Unrelated parameter 2 First value Handler constructor Unrelated parameter 4 s1:First value c.Prop:Prop s2:Second value literal:literal "); verifier.VerifyDiagnostics(); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$""literal"" + $""""")] public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression) { var code = @" using System; using System.Globalization; using System.Runtime.CompilerServices; int i = 1; C.M(i, " + expression + @"); public class C { public static implicit operator C(int i) => throw null; public static implicit operator C(double d) { Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture)); return new C(); } public override string ToString() => ""C""; public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" 1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 39 (0x27) .maxstack 5 .locals init (double V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: conv.r8 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.7 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""C C.op_Implicit(double)"" IL_000e: call ""CustomHandler..ctor(int, int, C)"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""literal"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: pop IL_0020: ldloc.1 IL_0021: call ""void C.M(double, CustomHandler)"" IL_0026: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { public int Prop { get; set; } public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); return 0; } set { Console.WriteLine(""Indexer setter""); Console.WriteLine(c.ToString()); } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter GetInt2 Indexer setter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 85 (0x55) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.s V_5 IL_0039: stloc.s V_4 IL_003b: ldloc.2 IL_003c: ldloc.3 IL_003d: ldloc.s V_4 IL_003f: ldloc.2 IL_0040: ldloc.3 IL_0041: ldloc.s V_4 IL_0043: callvirt ""int C.this[int, CustomHandler].get"" IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: callvirt ""void C.this[int, CustomHandler].set"" IL_0054: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 95 (0x5f) .maxstack 6 .locals init (int V_0, //i CustomHandler V_1, bool V_2, int V_3, C V_4, int V_5, CustomHandler V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.s V_4 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.3 IL_0010: ldloc.3 IL_0011: stloc.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.3 IL_0016: ldloc.s V_4 IL_0018: ldloca.s V_2 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001f: stloc.1 IL_0020: ldloc.2 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_1 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.1 IL_003f: stloc.s V_6 IL_0041: ldloc.s V_4 IL_0043: ldloc.s V_5 IL_0045: ldloc.s V_6 IL_0047: ldloc.s V_4 IL_0049: ldloc.s V_5 IL_004b: ldloc.s V_6 IL_004d: callvirt ""int C.this[int, CustomHandler].get"" IL_0052: ldc.i4.2 IL_0053: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0058: add IL_0059: callvirt ""void C.this[int, CustomHandler].set"" IL_005e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 91 (0x5b) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_5 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.s V_5 IL_003f: stloc.s V_4 IL_0041: ldloc.2 IL_0042: ldloc.3 IL_0043: ldloc.s V_4 IL_0045: ldloc.2 IL_0046: ldloc.3 IL_0047: ldloc.s V_4 IL_0049: callvirt ""int C.this[int, CustomHandler].get"" IL_004e: ldc.i4.2 IL_004f: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0054: add IL_0055: callvirt ""void C.this[int, CustomHandler].set"" IL_005a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 97 (0x61) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0041 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: brfalse.s IL_0041 IL_0030: ldloca.s V_5 IL_0032: ldloc.0 IL_0033: box ""int"" IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003f: br.s IL_0042 IL_0041: ldc.i4.0 IL_0042: pop IL_0043: ldloc.s V_5 IL_0045: stloc.s V_4 IL_0047: ldloc.2 IL_0048: ldloc.3 IL_0049: ldloc.s V_4 IL_004b: ldloc.2 IL_004c: ldloc.3 IL_004d: ldloc.s V_4 IL_004f: callvirt ""int C.this[int, CustomHandler].get"" IL_0054: ldc.i4.2 IL_0055: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_005a: add IL_005b: callvirt ""void C.this[int, CustomHandler].set"" IL_0060: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); Console.WriteLine(c.ToString()); return ref field; } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.this[int, CustomHandler].get"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 81 (0x51) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: stloc.3 IL_0012: ldc.i4.7 IL_0013: ldc.i4.1 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: ldloca.s V_5 IL_0018: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001d: stloc.s V_4 IL_001f: ldloc.s V_5 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_4 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.3 IL_003f: ldloc.s V_4 IL_0041: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0046: dup IL_0047: ldind.i4 IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: stind.i4 IL_0050: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC().M(GetInt(1), " + expression + @") += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c) { Console.WriteLine(""M""); Console.WriteLine(c.ToString()); return ref field; } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor M arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.M(int, CustomHandler)"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 81 (0x51) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: stloc.3 IL_0012: ldc.i4.7 IL_0013: ldc.i4.1 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: ldloca.s V_5 IL_0018: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001d: stloc.s V_4 IL_001f: ldloc.s V_5 IL_0021: brfalse.s IL_003e IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""void CustomHandler.AppendLiteral(string)"" IL_002f: ldloca.s V_4 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003e: ldloc.3 IL_003f: ldloc.s V_4 IL_0041: callvirt ""ref int C.M(int, CustomHandler)"" IL_0046: dup IL_0047: ldind.i4 IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: stind.i4 IL_0050: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.M(int, CustomHandler)"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.M(int, CustomHandler)"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression) { var code = @" using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; _ = new C(1) { " + expression + @" }; public class C : IEnumerable<int> { public int Field; public C(int i) { Field = i; } public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c) { Console.WriteLine(c.ToString()); } public IEnumerator<int> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => throw null; } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 5 .locals init (C V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_1 IL_000a: ldc.i4.7 IL_000b: ldc.i4.0 IL_000c: ldloc.0 IL_000d: call ""CustomHandler..ctor(int, int, C)"" IL_0012: ldloca.s V_1 IL_0014: ldstr ""literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: callvirt ""void C.Add(CustomHandler)"" IL_0024: ret } "); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_DictionaryInitializer(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(1) { [" + expression + @"] = 1 }; public class C { public int Field; public C(int i) { Field = i; } public int this[[InterpolatedStringHandlerArgument("""")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 40 (0x28) .maxstack 4 .locals init (C V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_2 IL_0009: ldc.i4.7 IL_000a: ldc.i4.0 IL_000b: ldloc.0 IL_000c: call ""CustomHandler..ctor(int, int, C)"" IL_0011: ldloca.s V_2 IL_0013: ldstr ""literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloc.2 IL_001e: stloc.1 IL_001f: ldloc.0 IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: callvirt ""void C.this[CustomHandler].set"" IL_0027: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler) { Console.WriteLine(handler.ToString()); } } public partial class CustomHandler { private int I = 0; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""int constructor""); I = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""CustomHandler constructor""); _builder.AppendLine(""c.I:"" + c.I.ToString()); " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c) { _builder.AppendLine(""CustomHandler AppendFormatted""); _builder.Append(c.ToString()); " + (useBoolReturns ? "return true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" int constructor CustomHandler constructor CustomHandler AppendFormatted c.I:1 literal:Inner string value:2 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 59 (0x3b) .maxstack 6 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: dup IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: ldc.i4.s 12 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0017: dup IL_0018: ldstr ""Inner string"" IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: box ""int"" IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: call ""void C.M(int, CustomHandler)"" IL_003a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 77 (0x4d) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_0046 IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0031 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0031: ldloc.s V_4 IL_0033: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0038: ldloc.1 IL_0039: ldc.i4.2 IL_003a: box ""int"" IL_003f: ldc.i4.0 IL_0040: ldnull IL_0041: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0046: ldloc.1 IL_0047: call ""void C.M(int, CustomHandler)"" IL_004c: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 68 (0x44) .maxstack 5 .locals init (int V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldc.i4.s 12 IL_0011: ldc.i4.0 IL_0012: ldloc.2 IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0018: dup IL_0019: ldstr ""Inner string"" IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_0029: brfalse.s IL_003b IL_002b: ldloc.1 IL_002c: ldc.i4.2 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.1 IL_003e: call ""void C.M(int, CustomHandler)"" IL_0043: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0033 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ldloc.s V_4 IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_003c: brfalse.s IL_004e IL_003e: ldloc.1 IL_003f: ldc.i4.2 IL_0040: box ""int"" IL_0045: ldc.i4.0 IL_0046: ldnull IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void DiscardsUsedAsParameters(string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(out _, " + expression + @"); public class C { public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) { i = 0; Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount) { i = 1; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 4 .locals init (int V_0, CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: ldstr ""literal"" IL_0013: call ""void CustomHandler.AppendLiteral(string)"" IL_0018: ldloc.1 IL_0019: call ""void C.M(out int, CustomHandler)"" IL_001e: ret } "); } [Fact] public void DiscardsUsedAsParameters_DefinedInVB() { var vb = @" Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler) Console.WriteLine(i) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer) i = 1 End Sub End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @"C.M(out _, $"""");"; var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() }); var verifier = CompileAndVerify(comp, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: call ""void C.M(out int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DisallowedInExpressionTrees(string expression) { var code = @" using System; using System.Linq.Expressions; Expression<Func<CustomHandler>> expr = () => " + expression + @"; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler }); comp.VerifyDiagnostics( // (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion. // Expression<Func<CustomHandler>> expr = () => $""; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46) ); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_01() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_02() { var code = @" using System.Linq.Expressions; Expression e = (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_03() { var code = @" using System; using System.Linq.Expressions; Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_04() { var code = @" using System; using System.Linq.Expressions; Expression e = Func<string, string> () => (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_05() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 167 (0xa7) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldstr ""literal"" IL_0073: ldtoken ""string"" IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0082: ldtoken ""string string.Concat(string, string)"" IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_008c: castclass ""System.Reflection.MethodInfo"" IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0096: ldc.i4.1 IL_0097: newarr ""System.Linq.Expressions.ParameterExpression"" IL_009c: dup IL_009d: ldc.i4.0 IL_009e: ldloc.0 IL_009f: stelem.ref IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a5: pop IL_00a6: ret } "); } [Theory] [CombinatorialData] public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @", " + expression + @"); public class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString()); } public partial class CustomHandler { private int i; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); this.i = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""c.i:"" + c.i.ToString()); " + (validityParameter ? "success = true;" : "") + @" } }"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", }; } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsFormattableString() { var code = @" M($""{1}"" + $""literal""); System.FormattableString s = $""{1}"" + $""literal""; void M(System.FormattableString s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.FormattableString' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.FormattableString").WithLocation(2, 3), // (3,30): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString' // System.FormattableString s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.FormattableString").WithLocation(3, 30) ); } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsIFormattable() { var code = @" M($""{1}"" + $""literal""); System.IFormattable s = $""{1}"" + $""literal""; void M(System.IFormattable s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.IFormattable' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.IFormattable").WithLocation(2, 3), // (3,25): error CS0029: Cannot implicitly convert type 'string' to 'System.IFormattable' // System.IFormattable s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.IFormattable").WithLocation(3, 25) ); } [Theory] [CombinatorialData] public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression) { var code = @" int i; string s; CustomHandler c = " + expression + @"; _ = i.ToString(); _ = o.ToString(); _ = s.ToString(); string M(out object o) { o = null; return null; } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (6,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5), // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else if (useBoolReturns) { comp.VerifyDiagnostics( // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression) { var code = @" int i; CustomHandler c = " + expression + @"; _ = i.ToString(); "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (5,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_01(string expression) { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_02(string expression) { var code = @" using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount) { Console.WriteLine(""d:"" + d.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "d:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: box ""int"" IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)"" IL_0010: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0015: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(dynamic literalLength, int formattedCount) { Console.WriteLine(""ctor""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: newobj ""CustomHandler..ctor(dynamic, int)"" IL_000c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0011: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { Console.WriteLine(""ctor""); } public CustomHandler(dynamic literalLength, int formattedCount) { throw null; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_000c: ret } "); } [Theory] [InlineData(@"$""Literal""")] [InlineData(@"$"""" + $""Literal""")] public void DynamicConstruction_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_0015: ldloc.0 IL_0016: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001b: ret } "); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""""")] public void DynamicConstruction_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 29 (0x1d) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)"" IL_0016: ldloc.0 IL_0017: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001c: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_08(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 128 (0x80) .maxstack 9 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0021: brtrue.s IL_0062 IL_0023: ldc.i4 0x100 IL_0028: ldstr ""AppendFormatted"" IL_002d: ldnull IL_002e: ldtoken ""Program"" IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0038: ldc.i4.2 IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003e: dup IL_003f: ldc.i4.0 IL_0040: ldc.i4.s 9 IL_0042: ldnull IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldc.i4.0 IL_004c: ldnull IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0052: stelem.ref IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target"" IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0071: ldloca.s V_1 IL_0073: ldloc.0 IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_0079: ldloc.1 IL_007a: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_007f: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_09(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public bool AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); return true; } public bool AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); return true; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 196 (0xc4) .maxstack 11 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)"" IL_001c: brfalse IL_00bb IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0026: brtrue.s IL_004c IL_0028: ldc.i4.0 IL_0029: ldtoken ""bool"" IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0033: ldtoken ""Program"" IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_0060: brtrue.s IL_009d IL_0062: ldc.i4.0 IL_0063: ldstr ""AppendFormatted"" IL_0068: ldnull IL_0069: ldtoken ""Program"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.2 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.s 9 IL_007d: ldnull IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0083: stelem.ref IL_0084: dup IL_0085: ldc.i4.1 IL_0086: ldc.i4.0 IL_0087: ldnull IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008d: stelem.ref IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00ac: ldloca.s V_1 IL_00ae: ldloc.0 IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00b9: br.s IL_00bc IL_00bb: ldc.i4.0 IL_00bc: pop IL_00bd: ldloc.1 IL_00be: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_00c3: ret } "); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_01(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // return $"{s}"; Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_02(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8150: By-value returns may only be used in methods that return by value // return $"{s}"; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return ref " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // return ref $"{s}"; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { S1 s1; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; } public void AppendFormatted(Span<char> s) => this.s1.s = s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s1, " + expression + @"); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9), // (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23) ); } [Theory] [InlineData(@"$""{s1}""")] [InlineData(@"$""{s1}"" + $""""")] public void RefEscape_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public void AppendFormatted(S1 s1) => s1.s = this.s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s, " + expression + @"); } public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_08() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public static CustomHandler M() { Span<char> s = stackalloc char[10]; ref CustomHandler c = ref M2(ref s, $""""); return c; } public static ref CustomHandler M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] ref CustomHandler handler) { return ref handler; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (16,16): error CS8352: Cannot use local 'c' in this context because it may expose referenced variables outside of their declaration scope // return c; Diagnostic(ErrorCode.ERR_EscapeLocal, "c").WithArguments("c").WithLocation(16, 16) ); } [Fact] public void RefEscape_09() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { s1.Handler = this; } public static void M(ref S1 s1) { Span<char> s2 = stackalloc char[10]; M2(ref s1, $""{s2}""); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler handler) { } public void AppendFormatted(Span<char> s) { this.s = s; } } public ref struct S1 { public CustomHandler Handler; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (15,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s2}"")").WithArguments("CustomHandler.M2(ref S1, CustomHandler)", "handler").WithLocation(15, 9), // (15,23): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(15, 23) ); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_01(string expression) { var code = @" int i = 1; System.Console.WriteLine(" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" { value:1 }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""{ "" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldstr "" }"" IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_002b: ldloca.s V_1 IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_02(string expression) { var code = @" int i = 1; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:{ value:1 alignment:0 format: literal: }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 71 (0x47) .maxstack 4 .locals init (int V_0, //i CustomHandler V_1, //c CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_2 IL_000d: ldstr ""{ "" IL_0012: call ""void CustomHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0026: ldloca.s V_2 IL_0028: ldstr "" }"" IL_002d: call ""void CustomHandler.AppendLiteral(string)"" IL_0032: ldloc.2 IL_0033: stloc.1 IL_0034: ldloca.s V_1 IL_0036: constrained. ""CustomHandler"" IL_003c: callvirt ""string object.ToString()"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ret } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 value:2 value:3 4 "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 66 (0x42) .maxstack 3 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 int V_3, //i4 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldc.i4.4 IL_0007: stloc.3 IL_0008: ldloca.s V_4 IL_000a: ldc.i4.0 IL_000b: ldc.i4.3 IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0011: ldloca.s V_4 IL_0013: ldloc.0 IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0019: ldloca.s V_4 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: ldloca.s V_4 IL_0023: ldloc.2 IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0029: ldloca.s V_4 IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0030: ldloca.s V_3 IL_0032: call ""string int.ToString()"" IL_0037: call ""string string.Concat(string, string)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""({i1}),"" + $""[{i2}],"" + $""{{{i3}}}""")] [InlineData(@"($""({i1}),"" + $""[{i2}],"") + $""{{{i3}}}""")] [InlineData(@"$""({i1}),"" + ($""[{i2}],"" + $""{{{i3}}}"")")] public void InterpolatedStringsAddedUnderObjectAddition2(string expression) { var code = $@" int i1 = 1; int i2 = 2; int i3 = 3; System.Console.WriteLine({expression});"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: @" ( value:1 ), [ value:2 ], { value:3 } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition3() { var code = @" #nullable enable using System; try { var s = string.Empty; Console.WriteLine($""{s = null}{s.Length}"" + $""""); } catch (NullReferenceException) { Console.WriteLine(""Null reference exception caught.""); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: "Null reference exception caught.").VerifyIL("<top-level-statements-entry-point>", @" { // Code size 65 (0x41) .maxstack 3 .locals init (string V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) .try { IL_0000: ldsfld ""string string.Empty"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: ldc.i4.2 IL_0008: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldnull IL_0011: dup IL_0012: stloc.0 IL_0013: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0018: ldloca.s V_1 IL_001a: ldloc.0 IL_001b: callvirt ""int string.Length.get"" IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: ldloca.s V_1 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: call ""void System.Console.WriteLine(string)"" IL_0031: leave.s IL_0040 } catch System.NullReferenceException { IL_0033: pop IL_0034: ldstr ""Null reference exception caught."" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: leave.s IL_0040 } IL_0040: ret } ").VerifyDiagnostics( // (9,36): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine($"{s = null}{s.Length}" + $""); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 36) ); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" object o1; object o2; object o3; _ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1; o1.ToString(); o2.ToString(); o3.ToString(); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); comp.VerifyDiagnostics( // (7,1): error CS0165: Use of unassigned local variable 'o2' // o2.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1), // (8,1): error CS0165: Use of unassigned local variable 'o3' // o3.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1) ); } [Theory] [InlineData(@"($""{i1}"" + $""{i2}"") + $""{i3}""")] [InlineData(@"$""{i1}"" + ($""{i2}"" + $""{i3}"")")] public void ParenthesizedAdditiveExpression_01(string expression) { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 82 (0x52) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 CustomHandler V_3, //c CustomHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldloca.s V_4 IL_0008: ldc.i4.0 IL_0009: ldc.i4.3 IL_000a: call ""CustomHandler..ctor(int, int)"" IL_000f: ldloca.s V_4 IL_0011: ldloc.0 IL_0012: box ""int"" IL_0017: ldc.i4.0 IL_0018: ldnull IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001e: ldloca.s V_4 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002d: ldloca.s V_4 IL_002f: ldloc.2 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldloc.s V_4 IL_003e: stloc.3 IL_003f: ldloca.s V_3 IL_0041: constrained. ""CustomHandler"" IL_0047: callvirt ""string object.ToString()"" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_02() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; CustomHandler c = /*<bind>*/((($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}""))) + (($""{i1}"" + ($""{i2}"" + $""{i3}"")) + (($""{i4}"" + $""{i5}"") + $""{i6}""))/*</bind>*/; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: value:4 alignment:0 format: value:5 alignment:0 format: value:6 alignment:0 format: value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: value:4 alignment:0 format: value:5 alignment:0 format: value:6 alignment:0 format: "); verifier.VerifyDiagnostics(); VerifyOperationTreeForTest<BinaryExpressionSyntax>(comp, @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '(($""{i1}"" + ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... ) + $""{i3}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + $""{i2}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + ( ... + $""{i6}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i5}"" + $""{i6}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... + $""{i6}"")') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + ( ... + $""{i3}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i2}"" + $""{i3}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i4}"" + ... ) + $""{i6}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + $""{i5}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null "); } [Fact] public void ParenthesizedAdditiveExpression_03() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = (($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}"")); System.Console.WriteLine(s);"; var verifier = CompileAndVerify(code, expectedOutput: @"123456"); verifier.VerifyDiagnostics(); } [Fact] public void ParenthesizedAdditiveExpression_04() { var code = @" using System.Threading.Tasks; int i1 = 2; int i2 = 3; string s = $""{await GetInt()}"" + ($""{i1}"" + $""{i2}""); System.Console.WriteLine(s); Task<int> GetInt() => Task.FromResult(1); "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }, expectedOutput: @" 1value:2 value:3"); verifier.VerifyDiagnostics(); // Note the two DefaultInterpolatedStringHandlers in the IL here. In a future rewrite step in the LocalRewriter, we can potentially // transform the tree to change its shape and pull out all individual Append calls in a sequence (regardless of the level of the tree) // and combine these and other unequal tree shapes. For now, we're going with a simple solution where, if the entire binary expression // cannot be combined, none of it is. verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 244 (0xf4) .maxstack 4 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004f IL_000a: ldarg.0 IL_000b: ldc.i4.2 IL_000c: stfld ""int Program.<<Main>$>d__0.<i1>5__2"" IL_0011: ldarg.0 IL_0012: ldc.i4.3 IL_0013: stfld ""int Program.<<Main>$>d__0.<i2>5__3"" IL_0018: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__GetInt|0_0()"" IL_001d: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0022: stloc.2 IL_0023: ldloca.s V_2 IL_0025: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002a: brtrue.s IL_006b IL_002c: ldarg.0 IL_002d: ldc.i4.0 IL_002e: dup IL_002f: stloc.0 IL_0030: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0035: ldarg.0 IL_0036: ldloc.2 IL_0037: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003c: ldarg.0 IL_003d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0042: ldloca.s V_2 IL_0044: ldarg.0 IL_0045: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004a: leave IL_00f3 IL_004f: ldarg.0 IL_0050: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0055: stloc.2 IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005c: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0062: ldarg.0 IL_0063: ldc.i4.m1 IL_0064: dup IL_0065: stloc.0 IL_0066: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006b: ldloca.s V_2 IL_006d: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0072: stloc.1 IL_0073: ldstr ""{0}"" IL_0078: ldloc.1 IL_0079: box ""int"" IL_007e: call ""string string.Format(string, object)"" IL_0083: ldc.i4.0 IL_0084: ldc.i4.1 IL_0085: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_008a: stloc.3 IL_008b: ldloca.s V_3 IL_008d: ldarg.0 IL_008e: ldfld ""int Program.<<Main>$>d__0.<i1>5__2"" IL_0093: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0098: ldloca.s V_3 IL_009a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_009f: ldc.i4.0 IL_00a0: ldc.i4.1 IL_00a1: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_00a6: stloc.3 IL_00a7: ldloca.s V_3 IL_00a9: ldarg.0 IL_00aa: ldfld ""int Program.<<Main>$>d__0.<i2>5__3"" IL_00af: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_00b4: ldloca.s V_3 IL_00b6: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00bb: call ""string string.Concat(string, string, string)"" IL_00c0: call ""void System.Console.WriteLine(string)"" IL_00c5: leave.s IL_00e0 } catch System.Exception { IL_00c7: stloc.s V_4 IL_00c9: ldarg.0 IL_00ca: ldc.i4.s -2 IL_00cc: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00d1: ldarg.0 IL_00d2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d7: ldloc.s V_4 IL_00d9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00de: leave.s IL_00f3 } IL_00e0: ldarg.0 IL_00e1: ldc.i4.s -2 IL_00e3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00e8: ldarg.0 IL_00e9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00f3: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_05() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; int i6 = 6; string s = /*<bind>*/((($""{i1}"" + $""{i2}"") + $""{i3}"") + ($""{i4}"" + ($""{i5}"" + $""{i6}""))) + (($""{i1}"" + ($""{i2}"" + $""{i3}"")) + (($""{i4}"" + $""{i5}"") + $""{i6}""))/*</bind>*/; System.Console.WriteLine(s);"; var comp = CreateCompilation(code); var verifier = CompileAndVerify(comp, expectedOutput: @"123456123456"); verifier.VerifyDiagnostics(); VerifyOperationTreeForTest<BinaryExpressionSyntax>(comp, @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '((($""{i1}"" ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '(($""{i1}"" + ... + $""{i6}""))') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... ) + $""{i3}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + $""{i2}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + ( ... + $""{i6}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i5}"" + $""{i6}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i1}"" + ... + $""{i6}"")') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i1}"" + ( ... + $""{i3}"")') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i1}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i1}') Expression: ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i2}"" + $""{i3}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i2}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i2}') Expression: ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i3}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i3}') Expression: ILocalReferenceOperation: i3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3') Alignment: null FormatString: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '($""{i4}"" + ... ) + $""{i6}""') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '$""{i4}"" + $""{i5}""') Left: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i4}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i4}') Expression: ILocalReferenceOperation: i4 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i4') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i5}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i5}') Expression: ILocalReferenceOperation: i5 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i5') Alignment: null FormatString: null Right: IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""{i6}""') Parts(1): IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i6}') Expression: ILocalReferenceOperation: i6 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i6') Alignment: null FormatString: null "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_01(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) = (" + initializer + @"); System.Console.Write(c1.ToString()); System.Console.WriteLine(c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 91 (0x5b) .maxstack 4 .locals init (CustomHandler V_0, //c1 CustomHandler V_1, //c2 CustomHandler V_2, CustomHandler V_3) IL_0000: ldloca.s V_3 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_3 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.0 IL_0012: ldnull IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0018: ldloc.3 IL_0019: stloc.2 IL_001a: ldloca.s V_3 IL_001c: ldc.i4.0 IL_001d: ldc.i4.1 IL_001e: call ""CustomHandler..ctor(int, int)"" IL_0023: ldloca.s V_3 IL_0025: ldc.i4.2 IL_0026: box ""int"" IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0032: ldloc.3 IL_0033: ldloc.2 IL_0034: stloc.0 IL_0035: stloc.1 IL_0036: ldloca.s V_0 IL_0038: constrained. ""CustomHandler"" IL_003e: callvirt ""string object.ToString()"" IL_0043: call ""void System.Console.Write(string)"" IL_0048: ldloca.s V_1 IL_004a: constrained. ""CustomHandler"" IL_0050: callvirt ""string object.ToString()"" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ret } "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_02(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) t = (" + initializer + @"); System.Console.Write(t.c1.ToString()); System.Console.WriteLine(t.c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 104 (0x68) .maxstack 6 .locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldc.i4.1 IL_000e: box ""int"" IL_0013: ldc.i4.0 IL_0014: ldnull IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001a: ldloc.1 IL_001b: ldloca.s V_1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.1 IL_001f: call ""CustomHandler..ctor(int, int)"" IL_0024: ldloca.s V_1 IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0033: ldloc.1 IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)"" IL_0039: ldloca.s V_0 IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1"" IL_0040: constrained. ""CustomHandler"" IL_0046: callvirt ""string object.ToString()"" IL_004b: call ""void System.Console.Write(string)"" IL_0050: ldloca.s V_0 IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2"" IL_0057: constrained. ""CustomHandler"" IL_005d: callvirt ""string object.ToString()"" IL_0062: call ""void System.Console.WriteLine(string)"" IL_0067: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{h1}{h2}""")] [InlineData(@"$""{h1}"" + $""{h2}""")] public void RefStructHandler_DynamicInHole(string expression) { var code = @" dynamic h1 = 1; dynamic h2 = 2; CustomHandler c = " + expression + ";"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "ref struct", useBoolReturns: false); var comp = CreateCompilationWithCSharp(new[] { code, handler }); // Note: We don't give any errors when mixing dynamic and ref structs today. If that ever changes, we should get an // error here. This will crash at runtime because of this. comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Literal{1}""")] [InlineData(@"$""Literal"" + $""{1}""")] public void ConversionInParamsArguments(string expression) { var code = @" using System; using System.Linq; M(" + expression + ", " + expression + @"); void M(params CustomHandler[] handlers) { Console.WriteLine(string.Join(Environment.NewLine, handlers.Select(h => h.ToString()))); } "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, expectedOutput: @" literal:Literal value:1 alignment:0 format: literal:Literal value:1 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 100 (0x64) .maxstack 7 .locals init (CustomHandler V_0) IL_0000: ldc.i4.2 IL_0001: newarr ""CustomHandler"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: ldc.i4.7 IL_000b: ldc.i4.1 IL_000c: call ""CustomHandler..ctor(int, int)"" IL_0011: ldloca.s V_0 IL_0013: ldstr ""Literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloca.s V_0 IL_001f: ldc.i4.1 IL_0020: box ""int"" IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002c: ldloc.0 IL_002d: stelem ""CustomHandler"" IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldloca.s V_0 IL_0036: ldc.i4.7 IL_0037: ldc.i4.1 IL_0038: call ""CustomHandler..ctor(int, int)"" IL_003d: ldloca.s V_0 IL_003f: ldstr ""Literal"" IL_0044: call ""void CustomHandler.AppendLiteral(string)"" IL_0049: ldloca.s V_0 IL_004b: ldc.i4.1 IL_004c: box ""int"" IL_0051: ldc.i4.0 IL_0052: ldnull IL_0053: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0058: ldloc.0 IL_0059: stelem ""CustomHandler"" IL_005e: call ""void Program.<<Main>$>g__M|0_0(CustomHandler[])"" IL_0063: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_01(string mod) { var code = @" using System.Runtime.CompilerServices; M($""""); " + mod + @" void M([InterpolatedStringHandlerArgument("""")] CustomHandler c) { } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (6,10): error CS8944: 'M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // void M([InterpolatedStringHandlerArgument("")] CustomHandler c) { } Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M(CustomHandler)").WithLocation(6, 10 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; M(1, $""""); " + mod + @" void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_01(string mod) { var code = @" using System.Runtime.CompilerServices; var a = " + mod + @" ([InterpolatedStringHandlerArgument("""")] CustomHandler c) => { }; a($""""); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,12): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument("""")").WithLocation(4, 12 + mod.Length), // (4,12): error CS8944: 'lambda expression' is not an instance method, the receiver cannot be an interpolated string handler argument. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("lambda expression").WithLocation(4, 12 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; var a = " + mod + @" (int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); a(1, $""""); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) => throw null; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @""); verifier.VerifyDiagnostics( // (5,19): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = (int i, [InterpolatedStringHandlerArgument("i")] CustomHandler c) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument(""i"")").WithLocation(5, 19 + mod.Length) ); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 4 IL_0000: ldsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""System.Action<int, CustomHandler>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: newobj ""CustomHandler..ctor(int, int)"" IL_0027: callvirt ""void System.Action<int, CustomHandler>.Invoke(int, CustomHandler)"" IL_002c: ret } "); } [Fact] public void ArgumentsOnDelegateTypes_01() { var code = @" using System.Runtime.CompilerServices; M m = null; m($""""); delegate void M([InterpolatedStringHandlerArgument("""")] CustomHandler c); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(6, 3), // (8,18): error CS8944: 'M.Invoke(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // delegate void M([InterpolatedStringHandlerArgument("")] CustomHandler c); Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M.Invoke(CustomHandler)").WithLocation(8, 18) ); } [Fact] public void ArgumentsOnDelegateTypes_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Delegate Sub M(<InterpolatedStringHandlerArgument("""")> c As CustomHandler) <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @" M m = null; m($""""); "; var comp = CreateCompilation(code, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(4, 3) ); } [Fact] public void ArgumentsOnDelegateTypes_03() { var code = @" using System; using System.Runtime.CompilerServices; M m = (i, c) => Console.WriteLine(c.ToString()); m(1, $""""); delegate void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 5 .locals init (int V_0) IL_0000: ldsfld ""M Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""M..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""M Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: stloc.0 IL_0021: ldloc.0 IL_0022: ldc.i4.0 IL_0023: ldc.i4.0 IL_0024: ldloc.0 IL_0025: newobj ""CustomHandler..ctor(int, int, int)"" IL_002a: callvirt ""void M.Invoke(int, CustomHandler)"" IL_002f: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_01() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private int _i = 0; public CustomHandler(int literalLength, int formattedCount, int i = 1) => _i = i; public override string ToString() => _i.ToString(); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: ldc.i4.1 IL_0003: newobj ""CustomHandler..ctor(int, int, int)"" IL_0008: call ""void C.M(CustomHandler)"" IL_000d: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_02() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""Literal""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, out bool isValid, int i = 1) { _s = i.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (CustomHandler V_0, bool V_1) IL_0000: ldc.i4.7 IL_0001: ldc.i4.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.1 IL_0005: newobj ""CustomHandler..ctor(int, int, out bool, int)"" IL_000a: stloc.0 IL_000b: ldloc.1 IL_000c: brfalse.s IL_001a IL_000e: ldloca.s V_0 IL_0010: ldstr ""Literal"" IL_0015: call ""void CustomHandler.AppendLiteral(string)"" IL_001a: ldloc.0 IL_001b: call ""void C.M(CustomHandler)"" IL_0020: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_03() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, int i2 = 2) { _s = i1.ToString() + i2.ToString(); } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 5 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldc.i4.2 IL_0007: newobj ""CustomHandler..ctor(int, int, int, int)"" IL_000c: call ""void C.M(int, CustomHandler)"" IL_0011: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_04() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""Literal""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, out bool isValid, int i2 = 2) { _s = i1.ToString() + i2.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.7 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: ldc.i4.2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool, int)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_001e IL_0012: ldloca.s V_1 IL_0014: ldstr ""Literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: call ""void C.M(int, CustomHandler)"" IL_0024: ret } "); } [Fact] public void HandlerExtensionMethod_01() { var code = @" $""Test"".M(); public static class StringExt { public static void M(this CustomHandler handler) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (2,1): error CS1929: 'string' does not contain a definition for 'M' and the best extension method overload 'StringExt.M(CustomHandler)' requires a receiver of type 'CustomHandler' // $"Test".M(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$""Test""").WithArguments("string", "M", "StringExt.M(CustomHandler)", "CustomHandler").WithLocation(2, 1) ); } [Fact] public void HandlerExtensionMethod_02() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument("""")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // s.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(5, 5), // (14,38): error CS8944: 'S1Ext.M(S1, CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M(this S1 s, [InterpolatedStringHandlerArgument("")] CustomHandler c) => throw null; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("S1Ext.M(S1, CustomHandler)").WithLocation(14, 38) ); } [Fact] public void HandlerExtensionMethod_03() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1"); verifier.VerifyDiagnostics(); } [Fact] public void NoStandaloneConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,19): error CS7036: There is no argument given that corresponds to the required formal parameter 's' of 'CustomHandler.CustomHandler(int, int, string)' // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("s", "CustomHandler.CustomHandler(int, int, string)").WithLocation(4, 19), // (4,19): error CS1615: Argument 3 may not be passed with the 'out' keyword // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(4, 19) ); } } }
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/Core.Cocoa/NavigationCommandHandlers/AbstractNavigationCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationCommandHandlers { internal abstract class AbstractNavigationCommandHandler<TCommandArgs> : VSCommanding.ICommandHandler<TCommandArgs> where TCommandArgs : Microsoft.VisualStudio.Text.Editor.Commanding.EditorCommandArgs { private readonly IEnumerable<Lazy<IStreamingFindUsagesPresenter>> _streamingPresenters; //private readonly IAsynchronousOperationListener _asyncListener; internal AbstractNavigationCommandHandler( IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters) { Contract.ThrowIfNull(streamingPresenters); _streamingPresenters = streamingPresenters; } public VSCommanding.CommandState GetCommandState(TCommandArgs args) { return VSCommanding.CommandState.Available; } public bool ExecuteCommand(TCommandArgs args, CommandExecutionContext context) { var snapshotSpans = (args.TextView.Selection as ITextSelection)?.GetSnapshotSpansOnBuffer(args.SubjectBuffer); if (snapshotSpans == null) return false; if (snapshotSpans.Count == 1) { var selectedSpan = snapshotSpans[0]; var snapshot = args.SubjectBuffer.CurrentSnapshot; var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { // Do a find-refs at the *start* of the selection. That way if the // user has selected a symbol that has another symbol touching it // on the right (i.e. Goo++ ), then we'll do the find-refs on the // symbol selected, not the symbol following. if (TryExecuteCommand(selectedSpan.Start, document, context)) { return true; } } } return false; } protected abstract bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context); internal IStreamingFindUsagesPresenter GetStreamingPresenter() { try { return _streamingPresenters.FirstOrDefault()?.Value; } catch { return null; } } public virtual string DisplayName => nameof(AbstractNavigationCommandHandler<TCommandArgs>); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationCommandHandlers { internal abstract class AbstractNavigationCommandHandler<TCommandArgs> : VSCommanding.ICommandHandler<TCommandArgs> where TCommandArgs : Microsoft.VisualStudio.Text.Editor.Commanding.EditorCommandArgs { private readonly IEnumerable<Lazy<IStreamingFindUsagesPresenter>> _streamingPresenters; //private readonly IAsynchronousOperationListener _asyncListener; internal AbstractNavigationCommandHandler( IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters) { Contract.ThrowIfNull(streamingPresenters); _streamingPresenters = streamingPresenters; } public VSCommanding.CommandState GetCommandState(TCommandArgs args) { return VSCommanding.CommandState.Available; } public bool ExecuteCommand(TCommandArgs args, CommandExecutionContext context) { var snapshotSpans = (args.TextView.Selection as ITextSelection)?.GetSnapshotSpansOnBuffer(args.SubjectBuffer); if (snapshotSpans == null) return false; if (snapshotSpans.Count == 1) { var selectedSpan = snapshotSpans[0]; var snapshot = args.SubjectBuffer.CurrentSnapshot; var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { // Do a find-refs at the *start* of the selection. That way if the // user has selected a symbol that has another symbol touching it // on the right (i.e. Goo++ ), then we'll do the find-refs on the // symbol selected, not the symbol following. if (TryExecuteCommand(selectedSpan.Start, document, context)) { return true; } } } return false; } protected abstract bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context); internal IStreamingFindUsagesPresenter GetStreamingPresenter() { try { return _streamingPresenters.FirstOrDefault()?.Value; } catch { return null; } } public virtual string DisplayName => nameof(AbstractNavigationCommandHandler<TCommandArgs>); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/NotKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class NotKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public NotKeywordRecommender() : base(SyntaxKind.NotKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsAtStartOfPattern; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class NotKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public NotKeywordRecommender() : base(SyntaxKind.NotKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsAtStartOfPattern; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/MetadataDefinitionItemEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { private class MetadataDefinitionItemEntry : AbstractItemEntry, ISupportsNavigation { public MetadataDefinitionItemEntry( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket) : base(definitionBucket, context.Presenter) { } protected override object? GetValueWorker(string keyName) { switch (keyName) { case StandardTableKeyNames.Text: return DefinitionBucket.DefinitionItem.DisplayParts.JoinText(); } return null; } public bool CanNavigateTo() => true; public Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken) => DefinitionBucket.DefinitionItem.TryNavigateToAsync( Presenter._workspace, showInPreviewTab: isPreview, activateTab: !isPreview, cancellationToken); // Only activate the tab if not opening in preview protected override IList<Inline> CreateLineTextInlines() => DefinitionBucket.DefinitionItem.DisplayParts .ToInlines(Presenter.ClassificationFormatMap, Presenter.TypeMap); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { private class MetadataDefinitionItemEntry : AbstractItemEntry, ISupportsNavigation { public MetadataDefinitionItemEntry( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket) : base(definitionBucket, context.Presenter) { } protected override object? GetValueWorker(string keyName) { switch (keyName) { case StandardTableKeyNames.Text: return DefinitionBucket.DefinitionItem.DisplayParts.JoinText(); } return null; } public bool CanNavigateTo() => true; public Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken) => DefinitionBucket.DefinitionItem.TryNavigateToAsync( Presenter._workspace, showInPreviewTab: isPreview, activateTab: !isPreview, cancellationToken); // Only activate the tab if not opening in preview protected override IList<Inline> CreateLineTextInlines() => DefinitionBucket.DefinitionItem.DisplayParts .ToInlines(Presenter.ClassificationFormatMap, Presenter.TypeMap); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/Test/TextEditor/TryGetDocumentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.TextEditor { [UseExportProvider] public class TryGetDocumentTests { [Fact] [WorkItem(624315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624315")] public void MultipleTextChangesTest() { var code = @"class C "; using var workspace = TestWorkspace.CreateCSharp(code); var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(workspace.GetDocumentId(hostDocument)); var buffer = hostDocument.GetTextBuffer(); var container = buffer.AsTextContainer(); var startPosition = buffer.CurrentSnapshot.GetLineFromLineNumber(1).Start.Position; buffer.Insert(startPosition, "{"); buffer.Insert(startPosition + 1, " "); buffer.Insert(startPosition + 2, "}"); var newDocument = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(); Assert.NotNull(newDocument); var expected = @"class C { }"; var newSourceText = newDocument.GetTextAsync().Result; Assert.Equal(expected, newSourceText.ToString()); Assert.True(container == newSourceText.Container); } [Fact] public void EmptyTextChanges() { var code = @"class C"; using var workspace = TestWorkspace.CreateCSharp(code); var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(workspace.GetDocumentId(hostDocument)); var buffer = hostDocument.GetTextBuffer(); var startingSnapshotVersion = buffer.CurrentSnapshot.Version; var text = buffer.CurrentSnapshot.AsText(); var container = buffer.AsTextContainer(); Assert.Same(text.Container, container); using (var edit = buffer.CreateEdit(EditOptions.DefaultMinimalChange, null, null)) { edit.Delete(0, 3); edit.Insert(0, "cla"); edit.Apply(); } Assert.Equal(startingSnapshotVersion.VersionNumber + 1, buffer.CurrentSnapshot.Version.VersionNumber); Assert.Equal(startingSnapshotVersion.VersionNumber, buffer.CurrentSnapshot.Version.ReiteratedVersionNumber); var newText = buffer.CurrentSnapshot.AsText(); // different buffer snapshot should never return same roslyn text snapshot Assert.NotSame(text, newText); var newDocument = newText.GetRelatedDocumentsWithChanges().First(); // different text snapshot never gives back same roslyn snapshot Assert.NotSame(document, newDocument); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.TextEditor { [UseExportProvider] public class TryGetDocumentTests { [Fact] [WorkItem(624315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624315")] public void MultipleTextChangesTest() { var code = @"class C "; using var workspace = TestWorkspace.CreateCSharp(code); var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(workspace.GetDocumentId(hostDocument)); var buffer = hostDocument.GetTextBuffer(); var container = buffer.AsTextContainer(); var startPosition = buffer.CurrentSnapshot.GetLineFromLineNumber(1).Start.Position; buffer.Insert(startPosition, "{"); buffer.Insert(startPosition + 1, " "); buffer.Insert(startPosition + 2, "}"); var newDocument = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(); Assert.NotNull(newDocument); var expected = @"class C { }"; var newSourceText = newDocument.GetTextAsync().Result; Assert.Equal(expected, newSourceText.ToString()); Assert.True(container == newSourceText.Container); } [Fact] public void EmptyTextChanges() { var code = @"class C"; using var workspace = TestWorkspace.CreateCSharp(code); var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(workspace.GetDocumentId(hostDocument)); var buffer = hostDocument.GetTextBuffer(); var startingSnapshotVersion = buffer.CurrentSnapshot.Version; var text = buffer.CurrentSnapshot.AsText(); var container = buffer.AsTextContainer(); Assert.Same(text.Container, container); using (var edit = buffer.CreateEdit(EditOptions.DefaultMinimalChange, null, null)) { edit.Delete(0, 3); edit.Insert(0, "cla"); edit.Apply(); } Assert.Equal(startingSnapshotVersion.VersionNumber + 1, buffer.CurrentSnapshot.Version.VersionNumber); Assert.Equal(startingSnapshotVersion.VersionNumber, buffer.CurrentSnapshot.Version.ReiteratedVersionNumber); var newText = buffer.CurrentSnapshot.AsText(); // different buffer snapshot should never return same roslyn text snapshot Assert.NotSame(text, newText); var newDocument = newText.GetRelatedDocumentsWithChanges().First(); // different text snapshot never gives back same roslyn snapshot Assert.NotSame(document, newDocument); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/Core.Wpf/SignatureHelp/SignatureHelpAfterCompletionCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CommandHandlers { /// <summary> /// There are two forms of intellisense that may be active at the same time. Completion and /// SigHelp. Completion precedes SigHelp in <see cref="SignatureHelpBeforeCompletionCommandHandler"/> /// because it wants to make sure /// it's operating on a buffer *after* Completion has changed it. i.e. if "WriteL(" is typed, /// sig help wants to allow completion to complete that to "WriteLine(" before it tried to /// proffer sig help. If we were to reverse things, then we'd get a bogus situation where sig /// help would see "WriteL(" would have nothing to offer and would return. /// /// However, despite wanting sighelp to receive typechar first and then defer it to completion, /// we want completion to receive other events first (like escape, and navigation keys). We /// consider completion to have higher priority for those commands. In order to accomplish that, /// we introduced the current command handler. This command handler then delegates escape, up and /// down to those command handlers. /// It is called after <see cref="PredefinedCompletionNames.CompletionCommandHandler"/>. /// </summary> [Export] [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] // Ensure roslyn comes after LSP to allow them to provide results. // https://github.com/dotnet/roslyn/issues/42338 [Order(After = "LSP SignatureHelpCommandHandler")] internal class SignatureHelpAfterCompletionCommandHandler : AbstractSignatureHelpCommandHandler, IChainedCommandHandler<EscapeKeyCommandArgs>, IChainedCommandHandler<UpKeyCommandArgs>, IChainedCommandHandler<DownKeyCommandArgs> { public string DisplayName => EditorFeaturesResources.Signature_Help; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SignatureHelpAfterCompletionCommandHandler( IThreadingContext threadingContext, SignatureHelpControllerProvider controllerProvider) : base(threadingContext, controllerProvider) { } public CommandState GetCommandState(EscapeKeyCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public CommandState GetCommandState(UpKeyCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public CommandState GetCommandState(DownKeyCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(EscapeKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { if (TryGetController(args, out var controller) && controller.TryHandleEscapeKey()) { return; } nextHandler(); } public void ExecuteCommand(UpKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { if (TryGetController(args, out var controller) && controller.TryHandleUpKey()) { return; } nextHandler(); } public void ExecuteCommand(DownKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { if (TryGetController(args, out var controller) && controller.TryHandleDownKey()) { return; } nextHandler(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CommandHandlers { /// <summary> /// There are two forms of intellisense that may be active at the same time. Completion and /// SigHelp. Completion precedes SigHelp in <see cref="SignatureHelpBeforeCompletionCommandHandler"/> /// because it wants to make sure /// it's operating on a buffer *after* Completion has changed it. i.e. if "WriteL(" is typed, /// sig help wants to allow completion to complete that to "WriteLine(" before it tried to /// proffer sig help. If we were to reverse things, then we'd get a bogus situation where sig /// help would see "WriteL(" would have nothing to offer and would return. /// /// However, despite wanting sighelp to receive typechar first and then defer it to completion, /// we want completion to receive other events first (like escape, and navigation keys). We /// consider completion to have higher priority for those commands. In order to accomplish that, /// we introduced the current command handler. This command handler then delegates escape, up and /// down to those command handlers. /// It is called after <see cref="PredefinedCompletionNames.CompletionCommandHandler"/>. /// </summary> [Export] [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] // Ensure roslyn comes after LSP to allow them to provide results. // https://github.com/dotnet/roslyn/issues/42338 [Order(After = "LSP SignatureHelpCommandHandler")] internal class SignatureHelpAfterCompletionCommandHandler : AbstractSignatureHelpCommandHandler, IChainedCommandHandler<EscapeKeyCommandArgs>, IChainedCommandHandler<UpKeyCommandArgs>, IChainedCommandHandler<DownKeyCommandArgs> { public string DisplayName => EditorFeaturesResources.Signature_Help; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SignatureHelpAfterCompletionCommandHandler( IThreadingContext threadingContext, SignatureHelpControllerProvider controllerProvider) : base(threadingContext, controllerProvider) { } public CommandState GetCommandState(EscapeKeyCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public CommandState GetCommandState(UpKeyCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public CommandState GetCommandState(DownKeyCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(EscapeKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { if (TryGetController(args, out var controller) && controller.TryHandleEscapeKey()) { return; } nextHandler(); } public void ExecuteCommand(UpKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { if (TryGetController(args, out var controller) && controller.TryHandleUpKey()) { return; } nextHandler(); } public void ExecuteCommand(DownKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { if (TryGetController(args, out var controller) && controller.TryHandleDownKey()) { return; } nextHandler(); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Core/Portable/DiaSymReader/Writer/SymUnmanagedWriterFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; namespace Microsoft.DiaSymReader { internal static class SymUnmanagedWriterFactory { /// <summary> /// Creates a Windows PDB writer. /// </summary> /// <param name="metadataProvider"><see cref="ISymWriterMetadataProvider"/> implementation.</param> /// <param name="options">Options.</param> /// <remarks> /// Tries to load the implementation of the PDB writer from Microsoft.DiaSymReader.Native.{platform}.dll library first. /// It searches for this library in the directory Microsoft.DiaSymReader.dll is loaded from, /// the application directory, the %WinDir%\System32 directory, and user directories in the DLL search path, in this order. /// If not found in the above locations and <see cref="SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath"/> option is specified /// the directory specified by MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH environment variable is also searched. /// If the Microsoft.DiaSymReader.Native.{platform}.dll library can't be found and <see cref="SymUnmanagedWriterCreationOptions.UseComRegistry"/> /// option is specified checks if the PDB reader is available from a globally registered COM object. This COM object is provided /// by .NET Framework and has limited functionality (features like determinism and source link are not supported). /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="metadataProvider"/>is null.</exception> /// <exception cref="DllNotFoundException">The SymWriter implementation is not available or failed to load.</exception> /// <exception cref="SymUnmanagedWriterException">Error creating the PDB writer. See inner exception for root cause.</exception> public static SymUnmanagedWriter CreateWriter( ISymWriterMetadataProvider metadataProvider, SymUnmanagedWriterCreationOptions options = SymUnmanagedWriterCreationOptions.Default) { if (metadataProvider == null) { throw new ArgumentNullException(nameof(metadataProvider)); } var symWriter = SymUnmanagedFactory.CreateObject( createReader: false, useAlternativeLoadPath: (options & SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath) != 0, useComRegistry: (options & SymUnmanagedWriterCreationOptions.UseComRegistry) != 0, moduleName: out var implModuleName, loadException: out var loadException); if (symWriter == null) { Debug.Assert(loadException != null); if (loadException is DllNotFoundException) { throw loadException; } throw new DllNotFoundException(loadException.Message, loadException); } if (!(symWriter is ISymUnmanagedWriter5 symWriter5)) { throw new SymUnmanagedWriterException(new NotSupportedException(), implModuleName); } object metadataEmitAndImport = new SymWriterMetadataAdapter(metadataProvider); var pdbStream = new ComMemoryStream(); try { if ((options & SymUnmanagedWriterCreationOptions.Deterministic) != 0) { if (symWriter is ISymUnmanagedWriter8 symWriter8) { symWriter8.InitializeDeterministic(metadataEmitAndImport, pdbStream); } else { throw new NotSupportedException(); } } else { // The file name is irrelevant as long as it's specified. // SymWriter only uses it for filling CodeView debug directory data when asked for them, but we never do. symWriter5.Initialize(metadataEmitAndImport, "filename.pdb", pdbStream, fullBuild: true); } } catch (Exception e) { throw new SymUnmanagedWriterException(e, implModuleName); } return new SymUnmanagedWriterImpl(pdbStream, symWriter5, implModuleName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; namespace Microsoft.DiaSymReader { internal static class SymUnmanagedWriterFactory { /// <summary> /// Creates a Windows PDB writer. /// </summary> /// <param name="metadataProvider"><see cref="ISymWriterMetadataProvider"/> implementation.</param> /// <param name="options">Options.</param> /// <remarks> /// Tries to load the implementation of the PDB writer from Microsoft.DiaSymReader.Native.{platform}.dll library first. /// It searches for this library in the directory Microsoft.DiaSymReader.dll is loaded from, /// the application directory, the %WinDir%\System32 directory, and user directories in the DLL search path, in this order. /// If not found in the above locations and <see cref="SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath"/> option is specified /// the directory specified by MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH environment variable is also searched. /// If the Microsoft.DiaSymReader.Native.{platform}.dll library can't be found and <see cref="SymUnmanagedWriterCreationOptions.UseComRegistry"/> /// option is specified checks if the PDB reader is available from a globally registered COM object. This COM object is provided /// by .NET Framework and has limited functionality (features like determinism and source link are not supported). /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="metadataProvider"/>is null.</exception> /// <exception cref="DllNotFoundException">The SymWriter implementation is not available or failed to load.</exception> /// <exception cref="SymUnmanagedWriterException">Error creating the PDB writer. See inner exception for root cause.</exception> public static SymUnmanagedWriter CreateWriter( ISymWriterMetadataProvider metadataProvider, SymUnmanagedWriterCreationOptions options = SymUnmanagedWriterCreationOptions.Default) { if (metadataProvider == null) { throw new ArgumentNullException(nameof(metadataProvider)); } var symWriter = SymUnmanagedFactory.CreateObject( createReader: false, useAlternativeLoadPath: (options & SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath) != 0, useComRegistry: (options & SymUnmanagedWriterCreationOptions.UseComRegistry) != 0, moduleName: out var implModuleName, loadException: out var loadException); if (symWriter == null) { Debug.Assert(loadException != null); if (loadException is DllNotFoundException) { throw loadException; } throw new DllNotFoundException(loadException.Message, loadException); } if (!(symWriter is ISymUnmanagedWriter5 symWriter5)) { throw new SymUnmanagedWriterException(new NotSupportedException(), implModuleName); } object metadataEmitAndImport = new SymWriterMetadataAdapter(metadataProvider); var pdbStream = new ComMemoryStream(); try { if ((options & SymUnmanagedWriterCreationOptions.Deterministic) != 0) { if (symWriter is ISymUnmanagedWriter8 symWriter8) { symWriter8.InitializeDeterministic(metadataEmitAndImport, pdbStream); } else { throw new NotSupportedException(); } } else { // The file name is irrelevant as long as it's specified. // SymWriter only uses it for filling CodeView debug directory data when asked for them, but we never do. symWriter5.Initialize(metadataEmitAndImport, "filename.pdb", pdbStream, fullBuild: true); } } catch (Exception e) { throw new SymUnmanagedWriterException(e, implModuleName); } return new SymUnmanagedWriterImpl(pdbStream, symWriter5, implModuleName); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/Core.Wpf/InlineRename/Dashboard/RenameShortcutKeys.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal class RenameShortcutKey { public static string RenameOverloads { get; } public static string SearchInStrings { get; } public static string SearchInComments { get; } public static string PreviewChanges { get; } public static string Apply { get; } public static string RenameFile { get; } static RenameShortcutKey() { RenameOverloads = ExtractAccessKey(EditorFeaturesResources.Include_overload_s, "O"); SearchInStrings = ExtractAccessKey(EditorFeaturesResources.Include_strings, "S"); SearchInComments = ExtractAccessKey(EditorFeaturesResources.Include_comments, "C"); PreviewChanges = ExtractAccessKey(EditorFeaturesResources.Preview_changes1, "P"); Apply = ExtractAccessKey(EditorFeaturesResources.Apply1, "A"); RenameFile = ExtractAccessKey(EditorFeaturesResources.Rename_symbols_file, "F"); } /// <summary> /// Given a localized label, searches for _ and extracts the accelerator key. If none found, /// returns defaultValue. /// </summary> private static string ExtractAccessKey(string localizedLabel, string defaultValue) { var underscoreIndex = localizedLabel.IndexOf('_'); if (underscoreIndex >= 0 && underscoreIndex < localizedLabel.Length - 1) { return new string(new char[] { char.ToUpperInvariant(localizedLabel[underscoreIndex + 1]) }); } Debug.Fail("Could not locate accelerator for " + localizedLabel + " for the rename dashboard"); return defaultValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal class RenameShortcutKey { public static string RenameOverloads { get; } public static string SearchInStrings { get; } public static string SearchInComments { get; } public static string PreviewChanges { get; } public static string Apply { get; } public static string RenameFile { get; } static RenameShortcutKey() { RenameOverloads = ExtractAccessKey(EditorFeaturesResources.Include_overload_s, "O"); SearchInStrings = ExtractAccessKey(EditorFeaturesResources.Include_strings, "S"); SearchInComments = ExtractAccessKey(EditorFeaturesResources.Include_comments, "C"); PreviewChanges = ExtractAccessKey(EditorFeaturesResources.Preview_changes1, "P"); Apply = ExtractAccessKey(EditorFeaturesResources.Apply1, "A"); RenameFile = ExtractAccessKey(EditorFeaturesResources.Rename_symbols_file, "F"); } /// <summary> /// Given a localized label, searches for _ and extracts the accelerator key. If none found, /// returns defaultValue. /// </summary> private static string ExtractAccessKey(string localizedLabel, string defaultValue) { var underscoreIndex = localizedLabel.IndexOf('_'); if (underscoreIndex >= 0 && underscoreIndex < localizedLabel.Length - 1) { return new string(new char[] { char.ToUpperInvariant(localizedLabel[underscoreIndex + 1]) }); } Debug.Fail("Could not locate accelerator for " + localizedLabel + " for the rename dashboard"); return defaultValue; } } }
-1